JSResourceEditor.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. modified_ = true;
  168. SetModified(true);
  169. autocomplete_->Hide();
  170. TBTextFragment* fragment = 0;
  171. int ofs = styleEdit_->caret.pos.ofs;
  172. fragment = styleEdit_->caret.pos.block->FindFragment(ofs, true);
  173. if (fragment && fragment->len && (styleEdit_->caret.pos.ofs == (fragment->ofs + fragment->len)))
  174. {
  175. String value(fragment->Str(), fragment->len);
  176. bool hasCompletions = autocomplete_->UpdateCompletions(value);
  177. if (hasCompletions)
  178. {
  179. autocomplete_->SetPosition(TBPoint(fragment->xpos, (styleEdit_->caret.y - styleEdit_->scroll_y) + fragment->line_height));
  180. // autocomplete disabled until it can be looked at
  181. //autocomplete_->Show();
  182. }
  183. }
  184. UpdateLineNumbers();
  185. }
  186. bool JSResourceEditor::OnEvent(const TBWidgetEvent &ev)
  187. {
  188. if (ev.type == EVENT_TYPE_KEY_DOWN)
  189. {
  190. if (autocomplete_ && autocomplete_->Visible())
  191. {
  192. return autocomplete_->OnEvent(ev);
  193. }
  194. if (ev.special_key == TB_KEY_ESC)
  195. {
  196. //SendEvent(E_FINDTEXTCLOSE);
  197. }
  198. }
  199. if (ev.type == EVENT_TYPE_SHORTCUT)
  200. {
  201. if (ev.ref_id == TBIDC("close"))
  202. {
  203. RequestClose();
  204. }
  205. if (ev.ref_id == TBIDC("find"))
  206. {
  207. //using namespace FindTextOpen;
  208. //SendEvent(E_FINDTEXTOPEN);
  209. }
  210. else if (ev.ref_id == TBIDC("findnext") || ev.ref_id == TBIDC("findprev"))
  211. {
  212. /*
  213. String text;
  214. FindTextWidget* finder = GetSubsystem<FindTextWidget>();
  215. finder->GetFindText(text);
  216. // TODO: get flags from finder
  217. unsigned flags = FINDTEXT_FLAG_NONE;
  218. if (ev.ref_id == TBIDC("findnext"))
  219. flags |= FINDTEXT_FLAG_NEXT;
  220. else if (ev.ref_id == TBIDC("findprev"))
  221. flags |= FINDTEXT_FLAG_PREV;
  222. flags |= FINDTEXT_FLAG_WRAP;
  223. finder->Find(text, flags);
  224. */
  225. }
  226. else if (ev.ref_id == TBIDC("cut") || ev.ref_id == TBIDC("copy") || ev.ref_id == TBIDC("paste")
  227. || ev.ref_id == TBIDC("selectall") || ev.ref_id == TBIDC("undo") || ev.ref_id == TBIDC("redo") )
  228. {
  229. editField_->OnEvent(ev);
  230. }
  231. }
  232. return false;
  233. }
  234. void JSResourceEditor::HandleUpdate(StringHash eventType, VariantMap& eventData)
  235. {
  236. if (!styleEdit_)
  237. return;
  238. // sync line number
  239. lineNumberList_->GetScrollContainer()->ScrollTo(0, styleEdit_->scroll_y);
  240. lineNumberList_->SetValue(styleEdit_->GetCaretLine());
  241. if (autocomplete_->Visible())
  242. {
  243. TBTextFragment* fragment = 0;
  244. int ofs = styleEdit_->caret.pos.ofs;
  245. fragment = styleEdit_->caret.pos.block->FindFragment(ofs, true);
  246. if (fragment && (styleEdit_->caret.pos.ofs == (fragment->ofs + fragment->len)))
  247. {
  248. String value(fragment->Str(), fragment->len);
  249. bool hasCompletions = autocomplete_->UpdateCompletions(value);
  250. if (!hasCompletions)
  251. {
  252. autocomplete_->Hide();
  253. }
  254. }
  255. }
  256. // Timestep parameter is same no matter what event is being listened to
  257. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  258. if (!textDirty_)
  259. return;
  260. if (textDelta_ > 0.0f)
  261. {
  262. textDelta_ -= timeStep;
  263. if (textDelta_ < 0.0f)
  264. {
  265. textDelta_ = 0.0f;
  266. }
  267. else
  268. {
  269. return;
  270. }
  271. }
  272. TBStr text;
  273. styleEdit_->GetText(text);
  274. JSASTProgram* program = NULL;
  275. String json;
  276. if (ParseJavascriptToJSON(text.CStr(), json))
  277. {
  278. program = JSASTProgram::ParseFromJSON("fullpath", json);
  279. if (program)
  280. {
  281. JSASTSyntaxColorVisitor syntaxColor(styleEdit_);
  282. syntaxColor.visit(program);
  283. delete program;
  284. }
  285. }
  286. textDirty_ = false;
  287. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  288. }
  289. void JSResourceEditor::FindTextClose()
  290. {
  291. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  292. styleEdit_->selection.SelectNothing();
  293. }
  294. bool JSResourceEditor::FindText(const String& findText, unsigned flags)
  295. {
  296. /*
  297. unsigned findLength = findText.Length();
  298. if (!findLength)
  299. return true;
  300. TBStr _source;
  301. styleEdit_->GetText(_source);
  302. String source = _source.CStr();
  303. unsigned pos = String::NPOS;
  304. int startPos = currentFindPos_;
  305. if (currentFindPos_ == -1)
  306. startPos = styleEdit_->caret.GetGlobalOfs();
  307. else
  308. {
  309. if (flags & FINDTEXT_FLAG_NEXT)
  310. startPos += findLength;
  311. }
  312. if (flags & FINDTEXT_FLAG_PREV)
  313. {
  314. String pretext = source.Substring(0, startPos);
  315. pos = pretext.FindLast(findText, String::NPOS, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  316. }
  317. else
  318. {
  319. pos = source.Find(findText, startPos, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  320. }
  321. if (pos == String::NPOS)
  322. {
  323. if (flags & FINDTEXT_FLAG_WRAP)
  324. {
  325. if (flags & FINDTEXT_FLAG_PREV)
  326. {
  327. pos = source.FindLast(findText, String::NPOS, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  328. }
  329. else
  330. {
  331. pos = source.Find(findText, 0, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  332. }
  333. }
  334. if (pos == String::NPOS)
  335. {
  336. styleEdit_->selection.SelectNothing();
  337. return true;
  338. }
  339. }
  340. currentFindPos_ = pos;
  341. styleEdit_->caret.SetGlobalOfs((int) pos + findLength);
  342. int height = styleEdit_->layout_height;
  343. int newy = styleEdit_->caret.y - height/2;
  344. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  345. styleEdit_->selection.Select(pos, pos + findLength);
  346. */
  347. return true;
  348. }
  349. void JSResourceEditor::SetFocus()
  350. {
  351. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  352. }
  353. void JSResourceEditor::GotoTokenPos(int tokenPos)
  354. {
  355. styleEdit_->caret.SetGlobalOfs(tokenPos);
  356. int height = styleEdit_->layout_height;
  357. int newy = styleEdit_->caret.y - height/2;
  358. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  359. }
  360. void JSResourceEditor::GotoLineNumber(int lineNumber)
  361. {
  362. int line = 0;
  363. TBBlock *block = NULL;
  364. for (block = styleEdit_->blocks.GetFirst(); block; block = block->GetNext())
  365. {
  366. if (lineNumber == line)
  367. break;
  368. line++;
  369. }
  370. if (!block)
  371. return;
  372. styleEdit_->caret.Place(block, 0);
  373. int height = styleEdit_->layout_height;
  374. int newy = styleEdit_->caret.y - height/2;
  375. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  376. }
  377. bool JSResourceEditor::ParseJavascriptToJSON(const char* source, String& json, bool loose)
  378. {
  379. JSVM* vm = JSVM::GetJSVM(NULL);
  380. duk_context* ctx = vm->GetJSContext();
  381. int top = duk_get_top(ctx);
  382. json.Clear();
  383. duk_get_global_string(ctx, "require");
  384. duk_push_string(ctx, "AtomicEditor/JavaScript/Lib/jsutils");
  385. if (duk_pcall(ctx, 1))
  386. {
  387. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  388. duk_set_top(ctx, top);
  389. return false;
  390. }
  391. duk_get_prop_string(ctx, -1, "parseToJSON");
  392. duk_push_string(ctx, source);
  393. bool ok = true;
  394. if (duk_pcall(ctx, 1))
  395. {
  396. ok = false;
  397. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  398. }
  399. else
  400. {
  401. json = duk_to_string(ctx, -1);
  402. }
  403. duk_set_top(ctx, top);
  404. return ok;
  405. }
  406. bool JSResourceEditor::BeautifyJavascript(const char* source, String& output)
  407. {
  408. JSVM* vm = JSVM::GetJSVM(NULL);
  409. duk_context* ctx = vm->GetJSContext();
  410. int top = duk_get_top(ctx);
  411. output.Clear();
  412. duk_get_global_string(ctx, "require");
  413. duk_push_string(ctx, "AtomicEditor/JavaScript/Lib/jsutils");
  414. if (duk_pcall(ctx, 1))
  415. {
  416. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  417. duk_set_top(ctx, top);
  418. return false;
  419. }
  420. duk_get_prop_string(ctx, -1, "jsBeautify");
  421. duk_push_string(ctx, source);
  422. bool ok = true;
  423. if (duk_pcall(ctx, 1))
  424. {
  425. ok = false;
  426. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  427. }
  428. else
  429. {
  430. output = duk_to_string(ctx, -1);
  431. }
  432. // ignore result
  433. duk_set_top(ctx, top);
  434. return ok;
  435. }
  436. bool JSResourceEditor::Save()
  437. {
  438. if (!modified_)
  439. return true;
  440. TBStr text;
  441. styleEdit_->GetText(text);
  442. File file(context_, fullpath_, FILE_WRITE);
  443. file.Write((void*) text.CStr(), text.Length());
  444. file.Close();
  445. SetModified(false);
  446. return true;
  447. }
  448. }