JSResourceEditor.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  2. // Please see LICENSE.md in repository root for license information
  3. // https://github.com/AtomicGameEngine/AtomicGameEngine
  4. #include "AtomicEditor.h"
  5. #include <Atomic/Container/ArrayPtr.h>
  6. #include <Atomic/UI/UI.h>
  7. #include <Atomic/IO/Log.h>
  8. #include <Atomic/IO/File.h>
  9. #include <Atomic/IO/FileSystem.h>
  10. #include <Atomic/Resource/ResourceCache.h>
  11. #include <Atomic/Core/CoreEvents.h>
  12. #include <AtomicJS/Javascript/JSVM.h>
  13. #include "JSResourceEditor.h"
  14. #include "../Javascript/JSAutocomplete.h"
  15. #include "../Javascript/JSTheme.h"
  16. #include "../Javascript/JSASTSyntaxColorVisitor.h"
  17. #include <TurboBadger/tb_message_window.h>
  18. #include <TurboBadger/tb_editfield.h>
  19. #include <TurboBadger/tb_style_edit.h>
  20. #include <TurboBadger/tb_style_edit_content.h>
  21. using namespace tb;
  22. namespace AtomicEditor
  23. {
  24. JSResourceEditor ::JSResourceEditor(Context* context, const String &fullpath, UITabContainer *container) :
  25. ResourceEditor(context, fullpath, container),
  26. styleEdit_(0),
  27. lineNumberList_(0),
  28. editField_(0),
  29. autocomplete_(0),
  30. textDirty_(true),
  31. textDelta_(0.0f),
  32. modified_(false),
  33. currentFindPos_(-1)
  34. {
  35. TBLayout* layout = new TBLayout();
  36. layout->SetLayoutSize(LAYOUT_SIZE_GRAVITY);
  37. layout->SetGravity(WIDGET_GRAVITY_ALL);
  38. layout->SetLayoutDistribution(LAYOUT_DISTRIBUTION_GRAVITY);
  39. rootContentWidget_->GetInternalWidget()->AddChild(layout);
  40. TBContainer* c = new TBContainer();
  41. c->SetGravity(WIDGET_GRAVITY_ALL);
  42. TBEditField* text = editField_ = new TBEditField();
  43. text->SetMultiline(true);
  44. text->SetWrapping(true);
  45. text->SetGravity(WIDGET_GRAVITY_ALL);
  46. text->SetStyling(true);
  47. text->SetSkinBg(TBIDC("TextCode"));
  48. TBFontDescription fd;
  49. fd.SetID(TBIDC("Monaco"));
  50. fd.SetSize(12);
  51. text->SetFontDescription(fd);
  52. SharedPtr<File> jsFile(GetSubsystem<ResourceCache>()->GetFile(fullpath));
  53. assert(jsFile);
  54. String source;
  55. jsFile->ReadText(source);
  56. String json;
  57. JSASTProgram* program = NULL;
  58. if (ParseJavascriptToJSON(source.CString(), json))
  59. {
  60. program = JSASTProgram::ParseFromJSON(fullpath, json);
  61. }
  62. text->SetText(source.CString());
  63. lineNumberList_ = new TBSelectList();
  64. lineNumberList_->SetFontDescription(fd);
  65. lineNumberList_->SetSkinBg(TBIDC("LineNumberSelectList"));
  66. lineNumberList_->GetScrollContainer()->SetScrollMode(SCROLL_MODE_OFF);
  67. //lineNumberList_->GetScrollContainer()->SetIgnoreScrollEvents(true);
  68. lineNumberList_->SetGravity(WIDGET_GRAVITY_ALL);
  69. LayoutParams lp;
  70. lp.max_w = 48;
  71. lineNumberList_->SetLayoutParams(lp);
  72. c->AddChild(text);
  73. layout->AddChild(lineNumberList_);
  74. layout->AddChild(c);
  75. layout->SetSpacing(0);
  76. TBStyleEdit* sedit = text->GetStyleEdit();
  77. TBTextTheme* theme = new TBTextTheme();
  78. for (unsigned i = 0; i < TB_MAX_TEXT_THEME_COLORS; i++)
  79. theme->themeColors[i] = TBColor(255, 255, 255);
  80. theme->themeColors[JSTHEME_LITERAL_STRING].SetFromString("#E6DB74", 7);
  81. theme->themeColors[JSTHEME_LITERAL_NUMBER].SetFromString("#AE81FF", 7);
  82. theme->themeColors[JSTHEME_LITERAL_REGEX].SetFromString("#AE81FF", 7);
  83. theme->themeColors[JSTHEME_LITERAL_BOOLEAN].SetFromString("#AE81FF", 7);
  84. theme->themeColors[JSTHEME_LITERAL_NULL].SetFromString("#AE81FF", 7);
  85. theme->themeColors[JSTHEME_FUNCTION].SetFromString("#66D9EF", 7);
  86. theme->themeColors[JSTHEME_VAR].SetFromString("#66D9EF", 7);
  87. theme->themeColors[JSTHEME_KEYWORD].SetFromString("#f92672", 7);
  88. theme->themeColors[JSTHEME_OPERATOR].SetFromString("#f92672", 7);
  89. theme->themeColors[JSTHEME_CODE].SetFromString("#a6e22e", 7);
  90. theme->themeColors[JSTHEME_COMMENT].SetFromString("#75715e", 7);
  91. theme->themeColors[JSTHEME_FUNCTIONDECLARG].SetFromString("#FF9800", 7);
  92. sedit->SetTextTheme(theme);
  93. sedit->text_change_listener = this;
  94. styleEdit_ = sedit;
  95. UpdateLineNumbers();
  96. if (program)
  97. {
  98. JSASTSyntaxColorVisitor syntaxColor(sedit);
  99. syntaxColor.visit(program);
  100. }
  101. autocomplete_ = new JSAutocomplete(text);
  102. autocomplete_->UpdateLocals();
  103. SubscribeToEvent(E_UPDATE, HANDLER(JSResourceEditor, HandleUpdate));
  104. // FIXME: Set the size at the end of setup, so all children are updated accordingly
  105. // future size changes will be handled automatically
  106. IntRect rect = container_->GetContentRoot()->GetRect();
  107. rootContentWidget_->SetSize(rect.Width(), rect.Height());
  108. }
  109. JSResourceEditor::~JSResourceEditor()
  110. {
  111. }
  112. void JSResourceEditor::FormatCode()
  113. {
  114. TBStr text;
  115. styleEdit_->GetText(text);
  116. if (text.Length())
  117. {
  118. String output;
  119. if (BeautifyJavascript(text.CStr(), output))
  120. {
  121. if (output.Length())
  122. {
  123. styleEdit_->selection.SelectAll();
  124. styleEdit_->InsertText(output.CString(), output.Length());
  125. }
  126. }
  127. }
  128. }
  129. void JSResourceEditor::UpdateLineNumbers()
  130. {
  131. if (!styleEdit_)
  132. return;
  133. TBGenericStringItemSource* lineSource = lineNumberList_->GetDefaultSource();
  134. int lines = lineSource->GetNumItems();
  135. int lineCount = styleEdit_->blocks.CountLinks();
  136. if (lines == lineCount)
  137. return;
  138. while (lines > lineCount)
  139. {
  140. lineSource->DeleteItem(lineSource->GetNumItems() - 1);
  141. lines --;
  142. }
  143. for (int i = lines; i < lineCount; i++)
  144. {
  145. String sline;
  146. sline.AppendWithFormat("%i ", i + 1);
  147. TBGenericStringItem* item = new TBGenericStringItem(sline.CString());
  148. lineSource->AddItem(item);
  149. }
  150. // item widgets don't exist until ValidateList
  151. lineNumberList_->ValidateList();
  152. for (int i = 0; i < lineCount; i++)
  153. {
  154. TBTextField* textField = (TBTextField* )lineNumberList_->GetItemWidget(i);
  155. if (textField)
  156. {
  157. textField->SetTextAlign(TB_TEXT_ALIGN_RIGHT);
  158. textField->SetSkinBg(TBIDC("TBSelectItemLineNumber"));
  159. }
  160. }
  161. }
  162. void JSResourceEditor::OnChange(TBStyleEdit* styleEdit)
  163. {
  164. textDelta_ = 0.25f;
  165. textDirty_ = true;
  166. modified_ = true;
  167. String filename = GetFileNameAndExtension(fullpath_);
  168. filename += "*";
  169. button_->SetText(filename.CString());
  170. autocomplete_->Hide();
  171. TBTextFragment* fragment = 0;
  172. int ofs = styleEdit_->caret.pos.ofs;
  173. fragment = styleEdit_->caret.pos.block->FindFragment(ofs, true);
  174. if (fragment && fragment->len && (styleEdit_->caret.pos.ofs == (fragment->ofs + fragment->len)))
  175. {
  176. String value(fragment->Str(), fragment->len);
  177. bool hasCompletions = autocomplete_->UpdateCompletions(value);
  178. if (hasCompletions)
  179. {
  180. autocomplete_->SetPosition(TBPoint(fragment->xpos, (styleEdit_->caret.y - styleEdit_->scroll_y) + fragment->line_height));
  181. // autocomplete disabled until it can be looked at
  182. //autocomplete_->Show();
  183. }
  184. }
  185. UpdateLineNumbers();
  186. }
  187. bool JSResourceEditor::OnEvent(const TBWidgetEvent &ev)
  188. {
  189. if (ev.type == EVENT_TYPE_KEY_DOWN)
  190. {
  191. if (autocomplete_ && autocomplete_->Visible())
  192. {
  193. return autocomplete_->OnEvent(ev);
  194. }
  195. if (ev.special_key == TB_KEY_ESC)
  196. {
  197. //SendEvent(E_FINDTEXTCLOSE);
  198. }
  199. }
  200. if (ev.type == EVENT_TYPE_SHORTCUT)
  201. {
  202. if (ev.ref_id == TBIDC("close"))
  203. {
  204. if (modified_)
  205. {
  206. TBMessageWindow *msg_win = new TBMessageWindow(container_->GetInternalWidget(), TBIDC("unsaved_jsmodifications_dialog"));
  207. TBMessageWindowSettings settings(TB_MSG_OK_CANCEL, TBID(uint32(0)));
  208. settings.dimmer = true;
  209. settings.styling = true;
  210. msg_win->Show("Unsaved Modifications", "There are unsaved modications.\nDo you wish to discard them and close?", &settings, 640, 360);
  211. }
  212. else
  213. {
  214. Close();
  215. }
  216. }
  217. if (ev.ref_id == TBIDC("find"))
  218. {
  219. //using namespace FindTextOpen;
  220. //SendEvent(E_FINDTEXTOPEN);
  221. }
  222. else if (ev.ref_id == TBIDC("findnext") || ev.ref_id == TBIDC("findprev"))
  223. {
  224. /*
  225. String text;
  226. FindTextWidget* finder = GetSubsystem<FindTextWidget>();
  227. finder->GetFindText(text);
  228. // TODO: get flags from finder
  229. unsigned flags = FINDTEXT_FLAG_NONE;
  230. if (ev.ref_id == TBIDC("findnext"))
  231. flags |= FINDTEXT_FLAG_NEXT;
  232. else if (ev.ref_id == TBIDC("findprev"))
  233. flags |= FINDTEXT_FLAG_PREV;
  234. flags |= FINDTEXT_FLAG_WRAP;
  235. finder->Find(text, flags);
  236. */
  237. }
  238. else if (ev.ref_id == TBIDC("cut") || ev.ref_id == TBIDC("copy") || ev.ref_id == TBIDC("paste")
  239. || ev.ref_id == TBIDC("selectall") || ev.ref_id == TBIDC("undo") || ev.ref_id == TBIDC("redo") )
  240. {
  241. editField_->OnEvent(ev);
  242. }
  243. }
  244. if (ev.type == EVENT_TYPE_CLICK)
  245. {
  246. if (ev.target->GetID() == TBIDC("unsaved_jsmodifications_dialog"))
  247. {
  248. if (ev.ref_id == TBIDC("TBMessageWindow.ok"))
  249. {
  250. Close();
  251. }
  252. else
  253. {
  254. SetFocus();
  255. }
  256. return true;
  257. }
  258. }
  259. return false;
  260. }
  261. void JSResourceEditor::HandleUpdate(StringHash eventType, VariantMap& eventData)
  262. {
  263. if (!styleEdit_)
  264. return;
  265. // sync line number
  266. lineNumberList_->GetScrollContainer()->ScrollTo(0, styleEdit_->scroll_y);
  267. lineNumberList_->SetValue(styleEdit_->GetCaretLine());
  268. if (autocomplete_->Visible())
  269. {
  270. TBTextFragment* fragment = 0;
  271. int ofs = styleEdit_->caret.pos.ofs;
  272. fragment = styleEdit_->caret.pos.block->FindFragment(ofs, true);
  273. if (fragment && (styleEdit_->caret.pos.ofs == (fragment->ofs + fragment->len)))
  274. {
  275. String value(fragment->Str(), fragment->len);
  276. bool hasCompletions = autocomplete_->UpdateCompletions(value);
  277. if (!hasCompletions)
  278. {
  279. autocomplete_->Hide();
  280. }
  281. }
  282. }
  283. // Timestep parameter is same no matter what event is being listened to
  284. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  285. if (!textDirty_)
  286. return;
  287. if (textDelta_ > 0.0f)
  288. {
  289. textDelta_ -= timeStep;
  290. if (textDelta_ < 0.0f)
  291. {
  292. textDelta_ = 0.0f;
  293. }
  294. else
  295. {
  296. return;
  297. }
  298. }
  299. TBStr text;
  300. styleEdit_->GetText(text);
  301. JSASTProgram* program = NULL;
  302. String json;
  303. if (ParseJavascriptToJSON(text.CStr(), json))
  304. {
  305. program = JSASTProgram::ParseFromJSON("fullpath", json);
  306. if (program)
  307. {
  308. JSASTSyntaxColorVisitor syntaxColor(styleEdit_);
  309. syntaxColor.visit(program);
  310. delete program;
  311. }
  312. }
  313. textDirty_ = false;
  314. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  315. }
  316. void JSResourceEditor::FindTextClose()
  317. {
  318. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  319. styleEdit_->selection.SelectNothing();
  320. }
  321. bool JSResourceEditor::FindText(const String& findText, unsigned flags)
  322. {
  323. /*
  324. unsigned findLength = findText.Length();
  325. if (!findLength)
  326. return true;
  327. TBStr _source;
  328. styleEdit_->GetText(_source);
  329. String source = _source.CStr();
  330. unsigned pos = String::NPOS;
  331. int startPos = currentFindPos_;
  332. if (currentFindPos_ == -1)
  333. startPos = styleEdit_->caret.GetGlobalOfs();
  334. else
  335. {
  336. if (flags & FINDTEXT_FLAG_NEXT)
  337. startPos += findLength;
  338. }
  339. if (flags & FINDTEXT_FLAG_PREV)
  340. {
  341. String pretext = source.Substring(0, startPos);
  342. pos = pretext.FindLast(findText, String::NPOS, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  343. }
  344. else
  345. {
  346. pos = source.Find(findText, startPos, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  347. }
  348. if (pos == String::NPOS)
  349. {
  350. if (flags & FINDTEXT_FLAG_WRAP)
  351. {
  352. if (flags & FINDTEXT_FLAG_PREV)
  353. {
  354. pos = source.FindLast(findText, String::NPOS, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  355. }
  356. else
  357. {
  358. pos = source.Find(findText, 0, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  359. }
  360. }
  361. if (pos == String::NPOS)
  362. {
  363. styleEdit_->selection.SelectNothing();
  364. return true;
  365. }
  366. }
  367. currentFindPos_ = pos;
  368. styleEdit_->caret.SetGlobalOfs((int) pos + findLength);
  369. int height = styleEdit_->layout_height;
  370. int newy = styleEdit_->caret.y - height/2;
  371. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  372. styleEdit_->selection.Select(pos, pos + findLength);
  373. */
  374. return true;
  375. }
  376. void JSResourceEditor::SetFocus()
  377. {
  378. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  379. }
  380. void JSResourceEditor::GotoTokenPos(int tokenPos)
  381. {
  382. styleEdit_->caret.SetGlobalOfs(tokenPos);
  383. int height = styleEdit_->layout_height;
  384. int newy = styleEdit_->caret.y - height/2;
  385. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  386. }
  387. void JSResourceEditor::GotoLineNumber(int lineNumber)
  388. {
  389. int line = 0;
  390. TBBlock *block = NULL;
  391. for (block = styleEdit_->blocks.GetFirst(); block; block = block->GetNext())
  392. {
  393. if (lineNumber == line)
  394. break;
  395. line++;
  396. }
  397. if (!block)
  398. return;
  399. styleEdit_->caret.Place(block, 0);
  400. int height = styleEdit_->layout_height;
  401. int newy = styleEdit_->caret.y - height/2;
  402. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  403. }
  404. bool JSResourceEditor::HasUnsavedModifications()
  405. {
  406. return modified_;
  407. }
  408. bool JSResourceEditor::ParseJavascriptToJSON(const char* source, String& json, bool loose)
  409. {
  410. JSVM* vm = JSVM::GetJSVM(NULL);
  411. duk_context* ctx = vm->GetJSContext();
  412. int top = duk_get_top(ctx);
  413. json.Clear();
  414. duk_get_global_string(ctx, "require");
  415. duk_push_string(ctx, "AtomicEditor/Script/jsutils");
  416. if (duk_pcall(ctx, 1))
  417. {
  418. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  419. duk_set_top(ctx, top);
  420. return false;
  421. }
  422. duk_get_prop_string(ctx, -1, "parseToJSON");
  423. duk_push_string(ctx, source);
  424. bool ok = true;
  425. if (duk_pcall(ctx, 1))
  426. {
  427. ok = false;
  428. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  429. }
  430. else
  431. {
  432. json = duk_to_string(ctx, -1);
  433. }
  434. duk_set_top(ctx, top);
  435. return ok;
  436. }
  437. bool JSResourceEditor::BeautifyJavascript(const char* source, String& output)
  438. {
  439. JSVM* vm = JSVM::GetJSVM(NULL);
  440. duk_context* ctx = vm->GetJSContext();
  441. int top = duk_get_top(ctx);
  442. output.Clear();
  443. duk_get_global_string(ctx, "require");
  444. duk_push_string(ctx, "AtomicEditor/modules/jsutils");
  445. if (duk_pcall(ctx, 1))
  446. {
  447. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  448. duk_set_top(ctx, top);
  449. return false;
  450. }
  451. duk_get_prop_string(ctx, -1, "jsBeautify");
  452. duk_push_string(ctx, source);
  453. bool ok = true;
  454. if (duk_pcall(ctx, 1))
  455. {
  456. ok = false;
  457. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  458. }
  459. else
  460. {
  461. output = duk_to_string(ctx, -1);
  462. }
  463. // ignore result
  464. duk_set_top(ctx, top);
  465. return ok;
  466. }
  467. bool JSResourceEditor::Save()
  468. {
  469. if (!modified_)
  470. return true;
  471. TBStr text;
  472. styleEdit_->GetText(text);
  473. File file(context_, fullpath_, FILE_WRITE);
  474. file.Write((void*) text.CStr(), text.Length());
  475. file.Close();
  476. String filename = GetFileNameAndExtension(fullpath_);
  477. button_->SetText(filename.CString());
  478. modified_ = false;
  479. return true;
  480. }
  481. }