JSResourceEditor.cpp 15 KB

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