Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(107)

Side by Side Diff: experimental/webtry/webtry.go

Issue 655633003: Revert of add ganesh checkbox to skfiddle interface (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Created 6 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « experimental/webtry/templates/template.gyp ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 package main 1 package main
2 2
3 import ( 3 import (
4 "bytes" 4 "bytes"
5 "crypto/md5" 5 "crypto/md5"
6 "database/sql" 6 "database/sql"
7 "encoding/base64" 7 "encoding/base64"
8 "encoding/binary" 8 "encoding/binary"
9 "encoding/json" 9 "encoding/json"
10 "flag" 10 "flag"
(...skipping 237 matching lines...) Expand 10 before | Expand all | Expand 10 after
248 )` 248 )`
249 _, err = db.Exec(sql) 249 _, err = db.Exec(sql)
250 if err != nil { 250 if err != nil {
251 log.Printf("Info: status creating sqlite table for sourc es: %q\n", err) 251 log.Printf("Info: status creating sqlite table for sourc es: %q\n", err)
252 } 252 }
253 253
254 sql = `CREATE TABLE IF NOT EXISTS webtry ( 254 sql = `CREATE TABLE IF NOT EXISTS webtry (
255 code TEXT DEFAULT '' NOT NULL, 255 code TEXT DEFAULT '' NOT NULL,
256 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, 256 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
257 hash CHAR(64) DEFAULT '' NOT NULL, 257 hash CHAR(64) DEFAULT '' NOT NULL,
258 width INTEGER DEFAULT 256 NOT NULL, 258 width »» » INTEGER DEFAULT 256 NOT NULL,
259 height INTEGER DEFAULT 256 NOT NULL, 259 height »» » INTEGER DEFAULT 256 NOT NULL,
260 gpu BOOL DEFAULT 0 NOT NULL,
261 source_image_id INTEGER DEFAULT 0 NOT NULL, 260 source_image_id INTEGER DEFAULT 0 NOT NULL,
262 261
263 PRIMARY KEY(hash) 262 PRIMARY KEY(hash)
264 )` 263 )`
265 _, err = db.Exec(sql) 264 _, err = db.Exec(sql)
266 if err != nil { 265 if err != nil {
267 log.Printf("Info: status creating sqlite table for webtr y: %q\n", err) 266 log.Printf("Info: status creating sqlite table for webtr y: %q\n", err)
268 } 267 }
269 268
270 sql = `CREATE TABLE IF NOT EXISTS workspace ( 269 sql = `CREATE TABLE IF NOT EXISTS workspace (
271 name CHAR(64) DEFAULT '' NOT NULL, 270 name CHAR(64) DEFAULT '' NOT NULL,
272 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, 271 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
273 PRIMARY KEY(name) 272 PRIMARY KEY(name)
274 )` 273 )`
275 _, err = db.Exec(sql) 274 _, err = db.Exec(sql)
276 if err != nil { 275 if err != nil {
277 log.Printf("Info: status creating sqlite table for works pace: %q\n", err) 276 log.Printf("Info: status creating sqlite table for works pace: %q\n", err)
278 } 277 }
279 278
280 sql = `CREATE TABLE IF NOT EXISTS workspacetry ( 279 sql = `CREATE TABLE IF NOT EXISTS workspacetry (
281 name CHAR(64) DEFAULT '' NOT NULL, 280 name CHAR(64) DEFAULT '' NOT NULL,
282 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, 281 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
283 hash CHAR(64) DEFAULT '' NOT NULL, 282 hash CHAR(64) DEFAULT '' NOT NULL,
284 width INTEGER DEFAULT 256 NOT NULL, 283 width » » INTEGER DEFAULT 256 NOT NULL,
285 height INTEGER DEFAULT 256 NOT NULL, 284 height » » INTEGER DEFAULT 256 NOT NULL,
286 gpu BOOL DEFAULT 0 NOT NULL,
287 hidden INTEGER DEFAULT 0 NOT NULL, 285 hidden INTEGER DEFAULT 0 NOT NULL,
288 source_image_id INTEGER DEFAULT 0 NOT NULL, 286 source_image_id INTEGER DEFAULT 0 NOT NULL,
289 287
290 FOREIGN KEY (name) REFERENCES workspace(name) 288 FOREIGN KEY (name) REFERENCES workspace(name)
291 )` 289 )`
292 _, err = db.Exec(sql) 290 _, err = db.Exec(sql)
293 if err != nil { 291 if err != nil {
294 log.Printf("Info: status creating sqlite table for works pace try: %q\n", err) 292 log.Printf("Info: status creating sqlite table for works pace try: %q\n", err)
295 } 293 }
296 } 294 }
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
349 GitHash string 347 GitHash string
350 GitInfo string 348 GitInfo string
351 } 349 }
352 350
353 // userCode is used in template expansion. 351 // userCode is used in template expansion.
354 type userCode struct { 352 type userCode struct {
355 Code string 353 Code string
356 Hash string 354 Hash string
357 Width int 355 Width int
358 Height int 356 Height int
359 GPU bool
360 Source int 357 Source int
361 Titlebar Titlebar 358 Titlebar Titlebar
362 } 359 }
363 360
364 // writeTemplate creates a given output file and writes the template 361 // writeTemplate creates a given output file and writes the template
365 // result there. 362 // result there.
366 func writeTemplate(filename string, t *template.Template, context interface{}) e rror { 363 func writeTemplate(filename string, t *template.Template, context interface{}) e rror {
367 f, err := os.Create(filename) 364 f, err := os.Create(filename)
368 if err != nil { 365 if err != nil {
369 return err 366 return err
370 } 367 }
371 defer f.Close() 368 defer f.Close()
372 return t.Execute(f, context) 369 return t.Execute(f, context)
373 } 370 }
374 371
375 // expandToFile expands the template and writes the result to the file. 372 // expandToFile expands the template and writes the result to the file.
376 func expandToFile(filename string, code string, t *template.Template) error { 373 func expandToFile(filename string, code string, t *template.Template) error {
377 return writeTemplate(filename, t, userCode{ 374 return writeTemplate(filename, t, userCode{
378 Code: code, 375 Code: code,
379 Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo}, 376 Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo},
380 }) 377 })
381 } 378 }
382 379
383 // expandCode expands the template into a file and calculates the MD5 hash. 380 // expandCode expands the template into a file and calculates the MD5 hash.
384 // We include the width and height here so that a single hash can capture 381 // We include the width and height here so that a single hash can capture
385 // both the code and the supplied width/height parameters. 382 // both the code and the supplied width/height parameters.
386 func expandCode(code string, source int, width, height int, gpu bool) (string, e rror) { 383 func expandCode(code string, source int, width, height int) (string, error) {
387 // in order to support fonts in the chroot jail, we need to make sure 384 // in order to support fonts in the chroot jail, we need to make sure
388 // we're using portable typefaces. 385 // we're using portable typefaces.
389 // TODO(humper): Make this more robust, supporting things like setTypef ace 386 // TODO(humper): Make this more robust, supporting things like setTypef ace
390 387
391 inputCodeLines := strings.Split(code, "\n") 388 inputCodeLines := strings.Split(code, "\n")
392 » outputCodeLines := []string{ 389 » outputCodeLines := []string{"DECLARE_bool(portableFonts);", fmt.Sprintf( "// WxH: %d, %d", width, height)}
393 » » "DECLARE_bool(portableFonts);",
394 » » fmt.Sprintf("// WxH: %d, %d", width, height),
395 » » fmt.Sprintf("// GPU: %v", gpu),
396 » }
397 for _, line := range inputCodeLines { 390 for _, line := range inputCodeLines {
398 outputCodeLines = append(outputCodeLines, line) 391 outputCodeLines = append(outputCodeLines, line)
399 if strings.HasPrefix(strings.TrimSpace(line), "SkPaint p") { 392 if strings.HasPrefix(strings.TrimSpace(line), "SkPaint p") {
400 outputCodeLines = append(outputCodeLines, "FLAGS_portabl eFonts = true;") 393 outputCodeLines = append(outputCodeLines, "FLAGS_portabl eFonts = true;")
401 outputCodeLines = append(outputCodeLines, "sk_tool_utils ::set_portable_typeface(&p, \"Helvetica\", SkTypeface::kNormal);") 394 outputCodeLines = append(outputCodeLines, "sk_tool_utils ::set_portable_typeface(&p, \"Helvetica\", SkTypeface::kNormal);")
402 } 395 }
403 } 396 }
404 397
405 fontFriendlyCode := strings.Join(outputCodeLines, "\n") 398 fontFriendlyCode := strings.Join(outputCodeLines, "\n")
406 399
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
465 log.Printf("Error: %s\n%s", message, err.Error()) 458 log.Printf("Error: %s\n%s", message, err.Error())
466 resp, err := json.Marshal(m) 459 resp, err := json.Marshal(m)
467 if err != nil { 460 if err != nil {
468 http.Error(w, "Failed to serialize a response", 500) 461 http.Error(w, "Failed to serialize a response", 500)
469 return 462 return
470 } 463 }
471 w.Header().Set("Content-Type", "text/plain") 464 w.Header().Set("Content-Type", "text/plain")
472 w.Write(resp) 465 w.Write(resp)
473 } 466 }
474 467
475 func writeToDatabase(hash string, code string, workspaceName string, source int, width, height int, gpu bool) { 468 func writeToDatabase(hash string, code string, workspaceName string, source int, width, height int) {
476 if db == nil { 469 if db == nil {
477 return 470 return
478 } 471 }
479 » if _, err := db.Exec("INSERT INTO webtry (code, hash, width, height, gpu , source_image_id) VALUES(?, ?, ?, ?, ?, ?)", code, hash, width, height, gpu, so urce); err != nil { 472 » if _, err := db.Exec("INSERT INTO webtry (code, hash, width, height, sou rce_image_id) VALUES(?, ?, ?, ?, ?)", code, hash, width, height, source); err != nil {
480 log.Printf("ERROR: Failed to insert code into database: %q\n", e rr) 473 log.Printf("ERROR: Failed to insert code into database: %q\n", e rr)
481 } 474 }
482 if workspaceName != "" { 475 if workspaceName != "" {
483 » » if _, err := db.Exec("INSERT INTO workspacetry (name, hash, widt h, height, gpu, source_image_id) VALUES(?, ?, ?, ?, ?, ?)", workspaceName, hash, width, height, gpu, source); err != nil { 476 » » if _, err := db.Exec("INSERT INTO workspacetry (name, hash, widt h, height, source_image_id) VALUES(?, ?, ?, ?, ?)", workspaceName, hash, width, height, source); err != nil {
484 log.Printf("ERROR: Failed to insert into workspacetry ta ble: %q\n", err) 477 log.Printf("ERROR: Failed to insert into workspacetry ta ble: %q\n", err)
485 } 478 }
486 } 479 }
487 } 480 }
488 481
489 type Sources struct { 482 type Sources struct {
490 Id int `json:"id"` 483 Id int `json:"id"`
491 } 484 }
492 485
493 // sourcesHandler serves up the PNG of a specific try. 486 // sourcesHandler serves up the PNG of a specific try.
(...skipping 122 matching lines...) Expand 10 before | Expand all | Expand 10 after
616 } 609 }
617 } 610 }
618 611
619 type Workspace struct { 612 type Workspace struct {
620 Name string 613 Name string
621 Code string 614 Code string
622 Hash string 615 Hash string
623 Width int 616 Width int
624 Height int 617 Height int
625 Source int 618 Source int
626 GPU bool
627 Tries []Try 619 Tries []Try
628 Titlebar Titlebar 620 Titlebar Titlebar
629 } 621 }
630 622
631 // newWorkspace generates a new random workspace name and stores it in the datab ase. 623 // newWorkspace generates a new random workspace name and stores it in the datab ase.
632 func newWorkspace() (string, error) { 624 func newWorkspace() (string, error) {
633 for i := 0; i < 10; i++ { 625 for i := 0; i < 10; i++ {
634 adj := workspaceNameAdj[rand.Intn(len(workspaceNameAdj))] 626 adj := workspaceNameAdj[rand.Intn(len(workspaceNameAdj))]
635 noun := workspaceNameNoun[rand.Intn(len(workspaceNameNoun))] 627 noun := workspaceNameNoun[rand.Intn(len(workspaceNameNoun))]
636 suffix := rand.Intn(1000) 628 suffix := rand.Intn(1000)
637 name := fmt.Sprintf("%s-%s-%d", adj, noun, suffix) 629 name := fmt.Sprintf("%s-%s-%d", adj, noun, suffix)
638 if _, err := db.Exec("INSERT INTO workspace (name) VALUES(?)", n ame); err == nil { 630 if _, err := db.Exec("INSERT INTO workspace (name) VALUES(?)", n ame); err == nil {
639 return name, nil 631 return name, nil
640 } else { 632 } else {
641 log.Printf("ERROR: Failed to insert workspace into datab ase: %q\n", err) 633 log.Printf("ERROR: Failed to insert workspace into datab ase: %q\n", err)
642 } 634 }
643 } 635 }
644 return "", fmt.Errorf("Failed to create a new workspace") 636 return "", fmt.Errorf("Failed to create a new workspace")
645 } 637 }
646 638
647 // getCode returns the code for a given hash, or the empty string if not found. 639 // getCode returns the code for a given hash, or the empty string if not found.
648 func getCode(hash string) (string, int, int, int, bool, error) { 640 func getCode(hash string) (string, int, int, int, error) {
649 code := "" 641 code := ""
650 width := 0 642 width := 0
651 height := 0 643 height := 0
652 source := 0 644 source := 0
653 » gpu := false 645 » if err := db.QueryRow("SELECT code, width, height, source_image_id FROM webtry WHERE hash=?", hash).Scan(&code, &width, &height, &source); err != nil {
654 » if err := db.QueryRow("SELECT code, width, height, gpu, source_image_id FROM webtry WHERE hash=?", hash).Scan(&code, &width, &height, &gpu, &source); er r != nil {
655 log.Printf("ERROR: Code for hash is missing: %q\n", err) 646 log.Printf("ERROR: Code for hash is missing: %q\n", err)
656 » » return code, width, height, source, gpu, err 647 » » return code, width, height, source, err
657 } 648 }
658 » return code, width, height, source, gpu, nil 649 » return code, width, height, source, nil
659 } 650 }
660 651
661 func workspaceHandler(w http.ResponseWriter, r *http.Request) { 652 func workspaceHandler(w http.ResponseWriter, r *http.Request) {
662 log.Printf("Workspace Handler: %q\n", r.URL.Path) 653 log.Printf("Workspace Handler: %q\n", r.URL.Path)
663 if r.Method == "GET" { 654 if r.Method == "GET" {
664 tries := []Try{} 655 tries := []Try{}
665 match := workspaceLink.FindStringSubmatch(r.URL.Path) 656 match := workspaceLink.FindStringSubmatch(r.URL.Path)
666 name := "" 657 name := ""
667 if len(match) == 2 { 658 if len(match) == 2 {
668 name = match[1] 659 name = match[1]
(...skipping 11 matching lines...) Expand all
680 continue 671 continue
681 } 672 }
682 tries = append(tries, Try{Hash: hash, Source: so urce, CreateTS: create_ts.Format("2006-02-01")}) 673 tries = append(tries, Try{Hash: hash, Source: so urce, CreateTS: create_ts.Format("2006-02-01")})
683 } 674 }
684 } 675 }
685 var code string 676 var code string
686 var hash string 677 var hash string
687 var width int 678 var width int
688 var height int 679 var height int
689 source := 0 680 source := 0
690 gpu := false
691 if len(tries) == 0 { 681 if len(tries) == 0 {
692 code = DEFAULT_SAMPLE 682 code = DEFAULT_SAMPLE
693 width = 256 683 width = 256
694 height = 256 684 height = 256
695 } else { 685 } else {
696 hash = tries[len(tries)-1].Hash 686 hash = tries[len(tries)-1].Hash
697 » » » code, width, height, source, gpu, _ = getCode(hash) 687 » » » code, width, height, source, _ = getCode(hash)
698 } 688 }
699 w.Header().Set("Content-Type", "text/html") 689 w.Header().Set("Content-Type", "text/html")
700 » » if err := workspaceTemplate.Execute(w, Workspace{Tries: tries, C ode: code, Name: name, Hash: hash, Width: width, Height: height, GPU: gpu, Sourc e: source, Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo}}); err != nil { 690 » » if err := workspaceTemplate.Execute(w, Workspace{Tries: tries, C ode: code, Name: name, Hash: hash, Width: width, Height: height, Source: source, Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo}}); err != nil {
701 log.Printf("ERROR: Failed to expand template: %q\n", err ) 691 log.Printf("ERROR: Failed to expand template: %q\n", err )
702 } 692 }
703 } else if r.Method == "POST" { 693 } else if r.Method == "POST" {
704 name, err := newWorkspace() 694 name, err := newWorkspace()
705 if err != nil { 695 if err != nil {
706 http.Error(w, "Failed to create a new workspace.", 500) 696 http.Error(w, "Failed to create a new workspace.", 500)
707 return 697 return
708 } 698 }
709 http.Redirect(w, r, "/w/"+name, 302) 699 http.Redirect(w, r, "/w/"+name, 302)
710 } 700 }
711 } 701 }
712 702
713 // hasPreProcessor returns true if any line in the code begins with a # char. 703 // hasPreProcessor returns true if any line in the code begins with a # char.
714 func hasPreProcessor(code string) bool { 704 func hasPreProcessor(code string) bool {
715 lines := strings.Split(code, "\n") 705 lines := strings.Split(code, "\n")
716 for _, s := range lines { 706 for _, s := range lines {
717 if strings.HasPrefix(strings.TrimSpace(s), "#") { 707 if strings.HasPrefix(strings.TrimSpace(s), "#") {
718 return true 708 return true
719 } 709 }
720 } 710 }
721 return false 711 return false
722 } 712 }
723 713
724 type TryRequest struct { 714 type TryRequest struct {
725 Code string `json:"code"` 715 Code string `json:"code"`
726 Width int `json:"width"` 716 Width int `json:"width"`
727 Height int `json:"height"` 717 Height int `json:"height"`
728 GPU bool `json:"gpu"`
729 Name string `json:"name"` // Optional name of the workspace the code is in. 718 Name string `json:"name"` // Optional name of the workspace the code is in.
730 Source int `json:"source"` // ID of the source image, 0 if none. 719 Source int `json:"source"` // ID of the source image, 0 if none.
731 } 720 }
732 721
733 // iframeHandler handles the GET and POST of the main page. 722 // iframeHandler handles the GET and POST of the main page.
734 func iframeHandler(w http.ResponseWriter, r *http.Request) { 723 func iframeHandler(w http.ResponseWriter, r *http.Request) {
735 log.Printf("IFrame Handler: %q\n", r.URL.Path) 724 log.Printf("IFrame Handler: %q\n", r.URL.Path)
736 if r.Method != "GET" { 725 if r.Method != "GET" {
737 http.NotFound(w, r) 726 http.NotFound(w, r)
738 return 727 return
739 } 728 }
740 match := iframeLink.FindStringSubmatch(r.URL.Path) 729 match := iframeLink.FindStringSubmatch(r.URL.Path)
741 if len(match) != 2 { 730 if len(match) != 2 {
742 http.NotFound(w, r) 731 http.NotFound(w, r)
743 return 732 return
744 } 733 }
745 hash := match[1] 734 hash := match[1]
746 if db == nil { 735 if db == nil {
747 http.NotFound(w, r) 736 http.NotFound(w, r)
748 return 737 return
749 } 738 }
750 var code string 739 var code string
751 » code, width, height, source, gpu, err := getCode(hash) 740 » code, width, height, source, err := getCode(hash)
752 if err != nil { 741 if err != nil {
753 http.NotFound(w, r) 742 http.NotFound(w, r)
754 return 743 return
755 } 744 }
756 // Expand the template. 745 // Expand the template.
757 w.Header().Set("Content-Type", "text/html") 746 w.Header().Set("Content-Type", "text/html")
758 » if err := iframeTemplate.Execute(w, userCode{Code: code, Width: width, H eight: height, GPU: gpu, Hash: hash, Source: source}); err != nil { 747 » if err := iframeTemplate.Execute(w, userCode{Code: code, Width: width, H eight: height, Hash: hash, Source: source}); err != nil {
759 log.Printf("ERROR: Failed to expand template: %q\n", err) 748 log.Printf("ERROR: Failed to expand template: %q\n", err)
760 } 749 }
761 } 750 }
762 751
763 type TryInfo struct { 752 type TryInfo struct {
764 Hash string `json:"hash"` 753 Hash string `json:"hash"`
765 Code string `json:"code"` 754 Code string `json:"code"`
766 Width int `json:"width"` 755 Width int `json:"width"`
767 Height int `json:"height"` 756 Height int `json:"height"`
768 GPU bool `json:"gpu"`
769 Source int `json:"source"` 757 Source int `json:"source"`
770 } 758 }
771 759
772 // tryInfoHandler returns information about a specific try. 760 // tryInfoHandler returns information about a specific try.
773 func tryInfoHandler(w http.ResponseWriter, r *http.Request) { 761 func tryInfoHandler(w http.ResponseWriter, r *http.Request) {
774 log.Printf("Try Info Handler: %q\n", r.URL.Path) 762 log.Printf("Try Info Handler: %q\n", r.URL.Path)
775 if r.Method != "GET" { 763 if r.Method != "GET" {
776 http.NotFound(w, r) 764 http.NotFound(w, r)
777 return 765 return
778 } 766 }
779 match := tryInfoLink.FindStringSubmatch(r.URL.Path) 767 match := tryInfoLink.FindStringSubmatch(r.URL.Path)
780 if len(match) != 2 { 768 if len(match) != 2 {
781 http.NotFound(w, r) 769 http.NotFound(w, r)
782 return 770 return
783 } 771 }
784 hash := match[1] 772 hash := match[1]
785 » code, width, height, source, gpu, err := getCode(hash) 773 » code, width, height, source, err := getCode(hash)
786 if err != nil { 774 if err != nil {
787 http.NotFound(w, r) 775 http.NotFound(w, r)
788 return 776 return
789 } 777 }
790 m := TryInfo{ 778 m := TryInfo{
791 Hash: hash, 779 Hash: hash,
792 Code: code, 780 Code: code,
793 Width: width, 781 Width: width,
794 Height: height, 782 Height: height,
795 GPU: gpu,
796 Source: source, 783 Source: source,
797 } 784 }
798 resp, err := json.Marshal(m) 785 resp, err := json.Marshal(m)
799 if err != nil { 786 if err != nil {
800 reportError(w, r, err, "Failed to serialize a response.") 787 reportError(w, r, err, "Failed to serialize a response.")
801 return 788 return
802 } 789 }
803 w.Header().Set("Content-Type", "application/json") 790 w.Header().Set("Content-Type", "application/json")
804 w.Write(resp) 791 w.Write(resp)
805 } 792 }
806 793
807 func cleanCompileOutput(s, hash string) string { 794 func cleanCompileOutput(s, hash string) string {
808 old := "../../../cache/src/" + hash + ".cpp:" 795 old := "../../../cache/src/" + hash + ".cpp:"
809 log.Printf("INFO: replacing %q\n", old) 796 log.Printf("INFO: replacing %q\n", old)
810 return strings.Replace(s, old, "usercode.cpp:", -1) 797 return strings.Replace(s, old, "usercode.cpp:", -1)
811 } 798 }
812 799
813 // mainHandler handles the GET and POST of the main page. 800 // mainHandler handles the GET and POST of the main page.
814 func mainHandler(w http.ResponseWriter, r *http.Request) { 801 func mainHandler(w http.ResponseWriter, r *http.Request) {
815 log.Printf("Main Handler: %q\n", r.URL.Path) 802 log.Printf("Main Handler: %q\n", r.URL.Path)
816 requestsCounter.Inc(1) 803 requestsCounter.Inc(1)
817 if r.Method == "GET" { 804 if r.Method == "GET" {
818 code := DEFAULT_SAMPLE 805 code := DEFAULT_SAMPLE
819 source := 0 806 source := 0
820 width := 256 807 width := 256
821 height := 256 808 height := 256
822 gpu := false
823 match := directLink.FindStringSubmatch(r.URL.Path) 809 match := directLink.FindStringSubmatch(r.URL.Path)
824 var hash string 810 var hash string
825 if len(match) == 2 && r.URL.Path != "/" { 811 if len(match) == 2 && r.URL.Path != "/" {
826 hash = match[1] 812 hash = match[1]
827 if db == nil { 813 if db == nil {
828 http.NotFound(w, r) 814 http.NotFound(w, r)
829 return 815 return
830 } 816 }
831 // Update 'code' with the code found in the database. 817 // Update 'code' with the code found in the database.
832 » » » if err := db.QueryRow("SELECT code, width, height, gpu, source_image_id FROM webtry WHERE hash=?", hash).Scan(&code, &width, &height, &g pu, &source); err != nil { 818 » » » if err := db.QueryRow("SELECT code, width, height, sourc e_image_id FROM webtry WHERE hash=?", hash).Scan(&code, &width, &height, &source ); err != nil {
833 http.NotFound(w, r) 819 http.NotFound(w, r)
834 return 820 return
835 } 821 }
836 } 822 }
837 // Expand the template. 823 // Expand the template.
838 w.Header().Set("Content-Type", "text/html") 824 w.Header().Set("Content-Type", "text/html")
839 » » if err := indexTemplate.Execute(w, userCode{Code: code, Hash: ha sh, Source: source, Width: width, Height: height, GPU: gpu, Titlebar: Titlebar{G itHash: gitHash, GitInfo: gitInfo}}); err != nil { 825 » » if err := indexTemplate.Execute(w, userCode{Code: code, Hash: ha sh, Source: source, Width: width, Height: height, Titlebar: Titlebar{GitHash: gi tHash, GitInfo: gitInfo}}); err != nil {
840 log.Printf("ERROR: Failed to expand template: %q\n", err ) 826 log.Printf("ERROR: Failed to expand template: %q\n", err )
841 } 827 }
842 } else if r.Method == "POST" { 828 } else if r.Method == "POST" {
843 w.Header().Set("Content-Type", "application/json") 829 w.Header().Set("Content-Type", "application/json")
844 buf := bytes.NewBuffer(make([]byte, 0, MAX_TRY_SIZE)) 830 buf := bytes.NewBuffer(make([]byte, 0, MAX_TRY_SIZE))
845 n, err := buf.ReadFrom(r.Body) 831 n, err := buf.ReadFrom(r.Body)
846 if err != nil { 832 if err != nil {
847 reportTryError(w, r, err, "Failed to read a request body .", "") 833 reportTryError(w, r, err, "Failed to read a request body .", "")
848 return 834 return
849 } 835 }
850 if n == MAX_TRY_SIZE { 836 if n == MAX_TRY_SIZE {
851 err := fmt.Errorf("Code length equal to, or exceeded, %d ", MAX_TRY_SIZE) 837 err := fmt.Errorf("Code length equal to, or exceeded, %d ", MAX_TRY_SIZE)
852 reportTryError(w, r, err, "Code too large.", "") 838 reportTryError(w, r, err, "Code too large.", "")
853 return 839 return
854 } 840 }
855 request := TryRequest{} 841 request := TryRequest{}
856 if err := json.Unmarshal(buf.Bytes(), &request); err != nil { 842 if err := json.Unmarshal(buf.Bytes(), &request); err != nil {
857 reportTryError(w, r, err, "Coulnd't decode JSON.", "") 843 reportTryError(w, r, err, "Coulnd't decode JSON.", "")
858 return 844 return
859 } 845 }
860 if hasPreProcessor(request.Code) { 846 if hasPreProcessor(request.Code) {
861 err := fmt.Errorf("Found preprocessor macro in code.") 847 err := fmt.Errorf("Found preprocessor macro in code.")
862 reportTryError(w, r, err, "Preprocessor macros aren't al lowed.", "") 848 reportTryError(w, r, err, "Preprocessor macros aren't al lowed.", "")
863 return 849 return
864 } 850 }
865 » » hash, err := expandCode(LineNumbers(request.Code), request.Sourc e, request.Width, request.Height, request.GPU) 851 » » hash, err := expandCode(LineNumbers(request.Code), request.Sourc e, request.Width, request.Height)
866 if err != nil { 852 if err != nil {
867 reportTryError(w, r, err, "Failed to write the code to c ompile.", hash) 853 reportTryError(w, r, err, "Failed to write the code to c ompile.", hash)
868 return 854 return
869 } 855 }
870 » » writeToDatabase(hash, request.Code, request.Name, request.Source , request.Width, request.Height, request.GPU) 856 » » writeToDatabase(hash, request.Code, request.Name, request.Source , request.Width, request.Height)
871 err = expandGyp(hash) 857 err = expandGyp(hash)
872 if err != nil { 858 if err != nil {
873 reportTryError(w, r, err, "Failed to write the gyp file. ", hash) 859 reportTryError(w, r, err, "Failed to write the gyp file. ", hash)
874 return 860 return
875 } 861 }
876 cmd := fmt.Sprintf("scripts/fiddle_wrapper %s --width %d --heigh t %d", hash, request.Width, request.Height) 862 cmd := fmt.Sprintf("scripts/fiddle_wrapper %s --width %d --heigh t %d", hash, request.Width, request.Height)
877 if request.GPU {
878 cmd += " --gpu"
879 }
880 if *useChroot { 863 if *useChroot {
881 cmd = "schroot -c webtry --directory=/ -- /skia_build/sk ia/experimental/webtry/" + cmd 864 cmd = "schroot -c webtry --directory=/ -- /skia_build/sk ia/experimental/webtry/" + cmd
882 } 865 }
883 if request.Source > 0 { 866 if request.Source > 0 {
884 cmd += fmt.Sprintf(" --source image-%d.png", request.Sou rce) 867 cmd += fmt.Sprintf(" --source image-%d.png", request.Sou rce)
885 } 868 }
886 869
887 message, err := doCmd(cmd) 870 message, err := doCmd(cmd)
888 if err != nil { 871 if err != nil {
889 reportTryError(w, r, err, "Failed to run the code:\n"+me ssage, hash) 872 reportTryError(w, r, err, "Failed to run the code:\n"+me ssage, hash)
(...skipping 30 matching lines...) Expand all
920 http.HandleFunc("/sources/", autogzip.HandleFunc(sourcesHandler)) 903 http.HandleFunc("/sources/", autogzip.HandleFunc(sourcesHandler))
921 904
922 // Resources are served directly 905 // Resources are served directly
923 // TODO add support for caching/etags/gzip 906 // TODO add support for caching/etags/gzip
924 http.Handle("/res/", autogzip.Handle(http.FileServer(http.Dir("./")))) 907 http.Handle("/res/", autogzip.Handle(http.FileServer(http.Dir("./"))))
925 908
926 // TODO Break out /c/ as it's own handler. 909 // TODO Break out /c/ as it's own handler.
927 http.HandleFunc("/", autogzip.HandleFunc(mainHandler)) 910 http.HandleFunc("/", autogzip.HandleFunc(mainHandler))
928 log.Fatal(http.ListenAndServe(*port, nil)) 911 log.Fatal(http.ListenAndServe(*port, nil))
929 } 912 }
OLDNEW
« no previous file with comments | « experimental/webtry/templates/template.gyp ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698