1 #include "studiox_includes.h"
2 #include "direct.h"
3 #include "wait_dialog.h"
4 
5 #ifdef _DEBUG
6 #define new DEBUG_NEW
7 #endif
8 
9 #define CHARMAP_SIZE_DEFAULT  8192
10 #define CHARMAP_SIZE_EXTENDED 262144
11 
12 
13 CBrush WinBackBrush(WIN_BACKGROUND_COLOR);
14 CBrush BlackBrush(RGB(0, 0, 0));
15 
16 wait_dialog *pWaitDialog = NULL;
17 int wait_nesting = 0;
18 BOOL is_guix_canvas_refresh_blocked = FALSE;
19 
20 INI_INFO StudioXIni;
21 CString   gOpenProjectDir;
22 
23 studiox_project *gpOpenProject = NULL;
24 
25 FILE _iob[] = { *stdin, *stdout, *stderr };
26 
__iob_func(void)27 extern "C" FILE * __cdecl __iob_func(void)
28 {
29     return _iob;
30 }
31 
32 
33 
34 ///////////////////////////////////////////////////////////////////////////////
SetOpenProject(studiox_project * open_project)35 void SetOpenProject(studiox_project *open_project)
36 {
37     gpOpenProject = open_project;
38 }
39 
40 ///////////////////////////////////////////////////////////////////////////////
GetOpenProject(void)41 studiox_project *GetOpenProject(void)
42 {
43     return gpOpenProject;
44 }
45 
46 ///////////////////////////////////////////////////////////////////////////////
project_lib_version(void)47 int project_lib_version(void)
48 {
49     if (gpOpenProject)
50     {
51         return gpOpenProject->mHeader.guix_version;
52     }
53     return 0;
54 }
55 
56 
57 ///////////////////////////////////////////////////////////////////////////////
BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lParam,LPARAM lpData)58 static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg, LPARAM lParam, LPARAM lpData)
59 {
60     // If the BFFM_INITIALIZED message is received
61     // set the path to the start path.
62     switch (uMsg)
63     {
64         case BFFM_INITIALIZED:
65         {
66             if (NULL != lpData)
67             {
68                 SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);
69             }
70         }
71     }
72 
73     return 0; // The function should always return 0.
74 }
75 
76 ///////////////////////////////////////////////////////////////////////////////
77 // HWND is the parent window.
78 // szCurrent is an optional start folder. Can be NULL.
79 // szPath receives the selected path on success. Must be MAX_PATH characters in length.
80 
BrowseForFolder(HWND hwnd,LPCTSTR caption,LPCTSTR szCurrent,LPTSTR szPath)81 BOOL BrowseForFolder(HWND hwnd, LPCTSTR caption, LPCTSTR szCurrent, LPTSTR szPath)
82 {
83     BROWSEINFO   bi = { 0 };
84     LPITEMIDLIST pidl;
85     TCHAR        szDisplay[MAX_PATH];
86     BOOL         retval;
87 
88     if (caption == NULL)
89     {
90         caption = _T("Please choose a folder...");
91     }
92     bi.hwndOwner      = hwnd;
93     bi.pszDisplayName = szDisplay;
94     bi.lpszTitle      = caption;
95     bi.ulFlags        = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
96     bi.lpfn           = BrowseCallbackProc;
97     bi.lParam         = (LPARAM) szCurrent;
98 
99     pidl = SHBrowseForFolder(&bi);
100 
101     if (NULL != pidl)
102     {
103         retval = SHGetPathFromIDList(pidl, szPath);
104         CoTaskMemFree(pidl);
105     }
106     else
107     {
108         retval = FALSE;
109     }
110 
111     if (!retval)
112     {
113         szPath[0] = TEXT('\0');
114     }
115 
116     //CoUninitialize();
117     return retval;
118 }
119 
120 ///////////////////////////////////////////////////////////////////////////////
MakeRelativePath(const CString & projpath,CString & filepath)121 BOOL MakeRelativePath(const CString &projpath, CString &filepath)
122 {
123     int index = 0;
124     int lastdir = 0;
125     BOOL dirfound = FALSE;
126     CString temp;
127 
128     // make sure path start with a drive letter:
129     if (filepath.IsEmpty() || filepath[1] != ':')
130     {
131         return FALSE;
132     }
133 
134     // check to make sure drive letters are the same:
135     if (toupper(projpath[0]) != toupper(filepath[0]))
136     {
137         return FALSE;
138     }
139 
140     while(1)
141     {
142         // are we at the end of either path?
143         if (!projpath[index] || !filepath[index])
144         {
145             break;
146         }
147 
148         // do the path strrings still match?
149         if (toupper(projpath[index]) != toupper(filepath[index]))
150         {
151             break;
152         }
153 
154         // if we are not at the end, keep track of the start
155         // of the last directory name:
156         if (filepath[index])
157         {
158             if (filepath[index] == ':' || filepath[index] == '\\')
159             {
160                 dirfound = TRUE;
161                 lastdir = index;
162             }
163             index++;
164         }
165     }
166 
167     if (filepath[index] || projpath[index])
168     {
169         // did we find any matching directories?
170         if (!dirfound)
171         {
172             return FALSE;
173         }
174 
175         // here if we found matching directories. If the project
176         // path is longer, then we need to back up:
177 
178         if (projpath[index])
179         {
180             temp = "..\\";
181             if (lastdir == index - 1)
182             {
183                 index++;
184             }
185         }
186         else
187         {
188             if (filepath[index] == '\\')
189             {
190                 lastdir = index;
191                 temp = "";
192             }
193         }
194 
195         // count directories remainin on project path, back up that
196         // many times
197         while(projpath[index])
198         {
199             if (projpath[index] == '\\' && projpath[index + 1] != 0)
200             {
201                 temp += "..\\";
202             }
203             index++;
204         }
205 
206         // skip past the delimiter
207         if (filepath[lastdir] == '\\')
208         {
209             lastdir++;
210         }
211         temp += filepath.Right(filepath.GetLength() - lastdir);
212         filepath = temp;
213     }
214     else
215     {
216         // if we get to here, then the project path and the requested
217         // path are exactly the same
218         filepath = ".\\";
219     }
220     return TRUE;
221 }
222 
223 ///////////////////////////////////////////////////////////////////////////////
ConvertToProjectRelativePath(CString & path)224 BOOL ConvertToProjectRelativePath(CString &path)
225 {
226     if (MakeRelativePath(gOpenProjectDir, path))
227     {
228         return TRUE;
229     }
230     return FALSE;
231 }
232 
233 ///////////////////////////////////////////////////////////////////////////////
SaveToPathInfo(PATHINFO & info,CString & path)234 void SaveToPathInfo(PATHINFO &info, CString &path)
235 {
236     info.pathname = path;
237 
238     switch(info.pathtype)
239     {
240     case PATH_TYPE_PROJECT_RELATIVE:
241         if (!ConvertToProjectRelativePath(info.pathname))
242         {
243             info.pathtype = PATH_TYPE_ABSOLUTE;
244         }
245         break;
246 
247     case PATH_TYPE_INSTALL_RELATIVE:
248         if (!MakeRelativePath(GetSamplesDir(), info.pathname))
249         {
250             info.pathtype = PATH_TYPE_ABSOLUTE;
251         }
252         break;
253 
254     default:
255         break;
256     }
257 }
258 
259 ///////////////////////////////////////////////////////////////////////////////
260 //C:\Renesas\guix_full_source_eval_for_rx_ylcdrx63n_iar\threadx\rx_ylcdrx63n\iar\demo_guix_medical
ConcatPathNames(CString & root,CString & extra)261 CString ConcatPathNames(CString &root, CString &extra)
262 {
263     CString base = root;
264     CString addition = extra;
265 
266     // trim leading ./ if it exists
267 
268     if (addition[0] == '.' &&
269         addition[1] == '\\')
270     {
271         addition = addition.Right(addition.GetLength() - 2);
272     }
273 
274     // for every ../ trim one directory from root
275 
276     while(addition.Find(_T("..\\")) == 0)
277     {
278         addition = addition.Right(addition.GetLength() - 3);
279         base = base.Left(base.ReverseFind('\\'));
280     }
281 
282     if (!addition.IsEmpty())
283     {
284         if (addition[0] != '\\')
285         {
286             base += '\\';
287         }
288         base += addition;
289     }
290     return base;
291 }
292 
293 ///////////////////////////////////////////////////////////////////////////////
MakeAbsolutePathname(PATHINFO & info)294 CString MakeAbsolutePathname(PATHINFO &info)
295 {
296     CString pathname;
297 
298     switch(info.pathtype)
299     {
300     case PATH_TYPE_ABSOLUTE:
301         pathname = info.pathname;
302         break;
303 
304     case PATH_TYPE_PROJECT_RELATIVE:
305         pathname = ConcatPathNames(gOpenProjectDir, info.pathname);
306         break;
307 
308     case PATH_TYPE_INSTALL_RELATIVE:
309         pathname = ConcatPathNames(GetSamplesDir(), info.pathname);
310         break;
311     }
312     return pathname;
313 }
314 
315 ///////////////////////////////////////////////////////////////////////////////
GotoProjectDirectory()316 void GotoProjectDirectory()
317 {
318     _tchdir(gOpenProjectDir.GetString());
319 }
320 
321 ///////////////////////////////////////////////////////////////////////////////
SetProjectDirectory(CString & path)322 void SetProjectDirectory(CString &path)
323 {
324     if (!PathIsRelative(path))
325     {
326         gOpenProjectDir = path;
327     }
328     else
329     {
330         TCHAR current_dir[MAX_PATH];
331         GetCurrentDirectory(MAX_PATH, current_dir);
332 
333         if ((path.GetAt(0) == '.') && (path.GetAt(1) != '.'))
334         {
335             path = path.Mid(1);
336         }
337 
338         gOpenProjectDir.Format(_T("%s\\%s"), current_dir, path);
339     }
340 }
341 
342 ///////////////////////////////////////////////////////////////////////////////
CheckOutputFileSecurity(CString & pathname,BOOL binary_mode)343 BOOL CheckOutputFileSecurity(CString &pathname, BOOL binary_mode)
344 {
345     int length = pathname.GetLength();
346     int index;
347     CString extension = L"";
348 
349     // Check for blacklisted directory in pathname
350 
351     if (pathname.Find(_T("Start Menu\\Programs")) >= 0)
352     {
353         CString error_msg = _T("Pathname is not allowed: ");
354         error_msg += pathname;
355         ErrorMsg(error_msg);
356         return FALSE;
357     }
358 
359     index = pathname.ReverseFind(L'.');
360 
361     if(index >= 0)
362     {
363         extension = pathname.Mid(index + 1);
364     }
365     else
366     {
367         index = pathname.GetLength();
368     }
369 
370     if (binary_mode)
371     {
372         if (extension != L"bin")
373         {
374             pathname = pathname.Left(index);
375             pathname += L".bin";
376         }
377     }
378     else
379     {
380         if (extension != L"c" && extension != L"h")
381         {
382             // strip the user-supplied extension and force the extension to .c
383             pathname = pathname.Left(index);
384             pathname += L".c";
385         }
386     }
387 
388     return TRUE;
389 }
390 
391 ///////////////////////////////////////////////////////////////////////////////
WriteToDosFile(CFile & outfile,CString & out)392 void WriteToDosFile(CFile &outfile, CString &out)
393 {
394     CString dos;
395     int start = 0;
396 
397     while(1)
398     {
399         int newline = out.Find('\n', start);
400 
401         if (newline < 0)
402         {
403             dos += out.Mid(start);
404             break;
405         }
406         if (newline > start)
407         {
408             dos += out.Mid(start, (newline - start));
409         }
410         start = newline + 1;
411         dos += "\r\n";
412     }
413 
414     outfile.Write(dos.GetBuffer(), dos.GetLength());
415 }
416 
417 ///////////////////////////////////////////////////////////////////////////////
CStringToWideChar(CString & text)418 wchar_t *CStringToWideChar(CString &text)
419 {
420 #ifdef _UNICODE
421     return text.GetBuffer();
422 #else if
423     wchar_t *uni_text;
424     int len = text.GetLength();
425 
426     if (len)
427     {
428         len++;
429         uni_text = new wchar_t[len];
430         MultiByteToWideChar(CP_UTF8, 0, text.GetBuffer(), -1, uni_text, len);
431         return uni_text;
432     }
433     return NULL;
434 #endif
435 }
436 
437 ///////////////////////////////////////////////////////////////////////////////
SelectDropListItem(CComboBox * box,long val)438 void SelectDropListItem(CComboBox *box, long val)
439 {
440     int box_index;
441 
442     for (box_index = 0; box_index < box->GetCount(); box_index++)
443     {
444         if (box->GetItemData(box_index) == val)
445         {
446             box->SetCurSel(box_index);
447         }
448     }
449 }
450 
451 ///////////////////////////////////////////////////////////////////////////////
RemoveFileExtension(CString & filename)452 CString RemoveFileExtension(CString &filename)
453 {
454     int pos = filename.ReverseFind('.');
455     if (pos > 0)
456     {
457         return filename.Left(pos);
458     }
459     return filename;
460 }
461 
462 ///////////////////////////////////////////////////////////////////////////////
ErrorMsg(const char * msg,CWnd * parent)463 void ErrorMsg(const char *msg, CWnd *parent)
464 {
465     /*Pick up command info. */
466     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
467     CCommandInfo *pCmdInfo = pMain->GetCmdInfo();
468 
469     if (!parent)
470     {
471         parent = AfxGetApp()->m_pMainWnd;
472     }
473 
474     if(!pCmdInfo->IsNoGui())
475     {
476         message_dialog dlg("Error", msg, false, parent);
477         dlg.DoModal();
478     }
479     else
480     {
481         if(pCmdInfo ->GetLogFile())
482         {
483             fprintf(pCmdInfo ->GetLogFile(), "%s\n",msg);
484         }
485     }
486 }
487 
488 ///////////////////////////////////////////////////////////////////////////////
ErrorMsg(const CString & msg,CWnd * parent)489 void ErrorMsg(const CString &msg, CWnd *parent)
490 {
491     /*Pick up command info. */
492     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
493     CCommandInfo *pCmdInfo = pMain->GetCmdInfo();
494 
495     if (!parent)
496     {
497         parent = AfxGetApp()->m_pMainWnd;
498     }
499 
500     if(!pCmdInfo->IsNoGui())
501     {
502         message_dialog dlg("Error", CW2A(msg), false, parent);
503         dlg.DoModal();
504     }
505     else
506     {
507         if(pCmdInfo ->GetLogFile())
508         {
509             fprintf(pCmdInfo->GetLogFile(), "%s\n", (char *)CW2A(msg));
510         }
511     }
512 }
513 
514 ///////////////////////////////////////////////////////////////////////////////
Notify(const char * msg,CWnd * parent)515 void Notify(const char *msg, CWnd *parent)
516 {
517     /*Pick up command info. */
518     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
519     CCommandInfo *pCmdInfo = pMain->GetCmdInfo();
520 
521     if (!parent)
522     {
523         parent = AfxGetApp()->m_pMainWnd;
524     }
525 
526     if(!pCmdInfo->IsNoGui())
527     {
528         message_dialog dlg("Notification", msg, false, parent);
529         dlg.DoModal();
530     }
531     else if(pCmdInfo ->GetLogFile())
532     {
533         fprintf(pCmdInfo ->GetLogFile(), "%s\n",msg);
534     }
535 }
536 
537 ///////////////////////////////////////////////////////////////////////////////
StartWorkThread(LPTHREAD_START_ROUTINE routine,LPVOID param,const char * msg,BOOL block_canvas_refresh)538 BOOL StartWorkThread(LPTHREAD_START_ROUTINE routine, LPVOID param, const char *msg, BOOL block_canvas_refresh)
539 {
540     CMainFrame* pMain = (CMainFrame*)AfxGetApp()->GetMainWnd();
541     CCommandInfo* pCmdInfo = pMain->GetCmdInfo();
542     BOOL result = TRUE;
543 
544     if (pCmdInfo->IsNoGui())
545     {
546         Notify(msg);
547         result = routine(param);
548     }
549     else
550     {
551         HANDLE hthread = CreateThread(NULL, GX_WIN32_STACK_SIZE, (LPTHREAD_START_ROUTINE)routine, (LPVOID)param, CREATE_SUSPENDED, 0);
552 
553         if ((hthread != INVALID_HANDLE_VALUE) && hthread)
554         {
555             is_guix_canvas_refresh_blocked = block_canvas_refresh;
556 
557             BusyMsg(msg, hthread);
558 
559             GetExitCodeThread(hthread, (LPDWORD)&result);
560 
561             CloseHandle(hthread);
562         }
563         else
564         {
565             result = FALSE;
566             ErrorMsg(L"Internal Error!");
567         }
568     }
569 
570     return result;
571 }
572 
573 ///////////////////////////////////////////////////////////////////////////////
IsWaitDialogRunning()574 BOOL IsWaitDialogRunning()
575 {
576     if (pWaitDialog)
577     {
578         return TRUE;
579     }
580 
581     return FALSE;
582 }
583 
584 ///////////////////////////////////////////////////////////////////////////////
IsGuixCanvasRefreshBlocked()585 BOOL IsGuixCanvasRefreshBlocked()
586 {
587     return is_guix_canvas_refresh_blocked;
588 }
589 
590 ///////////////////////////////////////////////////////////////////////////////
BusyMsg(const char * msg,HANDLE thread)591 void BusyMsg(const char *msg, HANDLE thread)
592 {
593     /*Pick up command info. */
594     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
595     CCommandInfo *pCmdInfo = pMain->GetCmdInfo();
596 
597     if(!pCmdInfo->IsNoGui())
598     {
599         wait_nesting++;
600 
601         if (wait_nesting == 1)
602         {
603             pWaitDialog = new wait_dialog(300, 120, msg, pMain);
604             pWaitDialog->SetWorkThread(thread);
605             pWaitDialog->DoModal();
606             delete pWaitDialog;
607             pWaitDialog = NULL;
608             is_guix_canvas_refresh_blocked = FALSE;
609         }
610         else
611         {
612             ResumeThread(thread);
613         }
614     }
615     else if(pCmdInfo ->GetLogFile())
616     {
617         fprintf(pCmdInfo ->GetLogFile(), "%s\n", msg);
618         ResumeThread(thread);
619     }
620 }
621 
622 ///////////////////////////////////////////////////////////////////////////////
EndBusyMsg(void)623 void EndBusyMsg(void)
624 {
625 
626     /*Pick up command info. */
627     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
628     CCommandInfo *pCmdInfo = pMain->GetCmdInfo();
629 
630     if(!pCmdInfo->IsNoGui())
631     {
632         if (wait_nesting > 0)
633         {
634             wait_nesting--;
635         }
636 
637         if (!wait_nesting)
638         {
639             pWaitDialog->SendMessage(WM_CLOSE, 0, 0);
640         }
641     }
642 }
643 
644 ///////////////////////////////////////////////////////////////////////////////
AskUser(const char * msg,CWnd * parent)645 BOOL AskUser(const char *msg, CWnd *parent)
646 {
647     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
648     CCommandInfo *pCmdInfo = pMain->GetCmdInfo();
649 
650     if(!pCmdInfo->IsNoGui())
651     {
652         if (parent == NULL)
653         {
654             parent = AfxGetApp()->m_pMainWnd;
655         }
656 
657         message_dialog dlg("Please Confirm", msg, true, parent);
658 
659         if (dlg.DoModal() == IDOK)
660         {
661             return TRUE;
662         }
663         return FALSE;
664     }
665     else
666     {
667         return TRUE;
668     }
669 }
670 
671 ///////////////////////////////////////////////////////////////////////////////
672 
673 
674 ///////////////////////////////////////////////////////////////////////////////
BrowseForSingleFile(LPCTSTR caption,LPCTSTR filter,LPCTSTR def_extension,CString & szPath,CWnd * parent)675 BOOL BrowseForSingleFile(LPCTSTR caption, LPCTSTR filter,
676     LPCTSTR def_extension, CString &szPath, CWnd *parent)
677 {
678     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
679 
680     OPENFILENAME OpenInfo;
681 
682     TCHAR SavePathname[MAX_PATH];
683     SavePathname[0] = 0;
684     szPath = _T("");
685 
686     OpenInfo.lStructSize = sizeof(OPENFILENAME);
687     OpenInfo.hwndOwner = parent->m_hWnd;
688     OpenInfo.hInstance = NULL;
689     OpenInfo.lpstrFilter = filter;
690     OpenInfo.lpstrCustomFilter = NULL;
691     OpenInfo.lpstrFile = SavePathname;
692     OpenInfo.nMaxFile = MAX_PATH;
693     OpenInfo.lpstrFileTitle = NULL;
694 
695     if (pMain->IsTestMode())
696     {
697         OpenInfo.lpstrInitialDir = gOpenProjectDir;
698     }
699     else
700     {
701         OpenInfo.lpstrInitialDir = NULL;
702     }
703 
704     OpenInfo.lpstrTitle = caption;
705     OpenInfo.lpstrDefExt = def_extension;
706 
707     OpenInfo.Flags = (OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_EXPLORER);
708 
709     if (GetOpenFileName(&OpenInfo))
710     {
711         szPath = SavePathname;
712         return TRUE;
713     }
714     return FALSE;
715 }
716 
717 ///////////////////////////////////////////////////////////////////////////////
BrowseForMultipleFiles(TCHAR * caption,TCHAR * filter,TCHAR * def_extension,TCHAR ** pathptr,TCHAR ** nameptr,CWnd * parent)718 int BrowseForMultipleFiles(TCHAR *caption, TCHAR * filter, TCHAR *def_extension,
719                            TCHAR **pathptr, TCHAR **nameptr, CWnd *parent)
720 {
721     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
722 
723     OPENFILENAME OpenInfo;
724     int NumFiles = 0;
725     int NameLen;
726     TCHAR *pGet;
727 
728 
729     TCHAR *pSavePath = new TCHAR[MAX_PATH * MAX_OPEN_FILES + 1];
730     pSavePath[0] = 0;
731     //szPath = _T("");
732 
733 
734     OpenInfo.lStructSize = sizeof(OPENFILENAME);
735     OpenInfo.hwndOwner = parent->m_hWnd;
736     OpenInfo.hInstance = NULL;
737     OpenInfo.lpstrFilter = filter;
738     OpenInfo.lpstrCustomFilter = NULL;
739     OpenInfo.lpstrFile = pSavePath;
740     OpenInfo.nMaxFile = MAX_PATH * MAX_OPEN_FILES;
741     OpenInfo.lpstrFileTitle = NULL;
742 
743     if (pMain->IsTestMode())
744     {
745         OpenInfo.lpstrInitialDir = gOpenProjectDir;
746     }
747     else
748     {
749         OpenInfo.lpstrInitialDir = NULL;
750     }
751 
752     OpenInfo.lpstrTitle = caption;
753     OpenInfo.lpstrDefExt = def_extension;
754 
755     OpenInfo.Flags = (OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|
756         OFN_EXPLORER|OFN_ALLOWMULTISELECT);
757 
758     if (GetOpenFileName(&OpenInfo))
759     {
760         pGet = pSavePath;
761         while(*pGet)
762         {
763             NumFiles++;
764             NameLen = (int) _tcslen(pGet) + 1;
765             pGet += NameLen;
766         }
767     }
768     if (NumFiles > 0)
769     {
770         *pathptr = pSavePath;
771         *nameptr = pSavePath + OpenInfo.nFileOffset;
772     }
773     else
774     {
775         *pathptr = NULL;
776         *nameptr = NULL;
777         delete [] pSavePath;
778     }
779     return NumFiles;
780 }
781 
782 ///////////////////////////////////////////////////////////////////////////////
GetOutputFileName(TCHAR * SavePathname,TCHAR * SaveFilename,TCHAR * title,TCHAR * filter,TCHAR * initial_dir,TCHAR * def_extension,CWnd * parent)783 BOOL GetOutputFileName(TCHAR *SavePathname, TCHAR *SaveFilename,
784                        TCHAR *title, TCHAR *filter, TCHAR *initial_dir,
785                        TCHAR *def_extension, CWnd *parent)
786 {
787 
788     OPENFILENAME OpenInfo;
789 
790     if (!parent)
791     {
792         parent = AfxGetMainWnd();
793     }
794 
795     OpenInfo.lStructSize = sizeof(OPENFILENAME);
796     OpenInfo.hwndOwner = parent->m_hWnd;
797     OpenInfo.hInstance = NULL;
798     OpenInfo.lpstrFilter = filter;
799     OpenInfo.lpstrCustomFilter = NULL;
800     OpenInfo.lpstrFile = SavePathname;
801     OpenInfo.nMaxFile = MAX_PATH;
802     OpenInfo.lpstrFileTitle = SaveFilename;
803     OpenInfo.nMaxFileTitle = MAX_PATH;
804     OpenInfo.lpstrInitialDir = initial_dir;
805     OpenInfo.lpstrTitle = title;
806     OpenInfo.lpstrDefExt = def_extension;
807 
808     OpenInfo.Flags = (OFN_PATHMUSTEXIST|OFN_EXPLORER);
809 
810     if (GetOpenFileName(&OpenInfo))
811     {
812         return TRUE;
813     }
814     return FALSE;
815 }
816 
817 ///////////////////////////////////////////////////////////////////////////////
MakePath(CString path)818 void MakePath(CString path)
819 {
820     int index = 0;
821 
822     if (_tchdir(path) != 0)
823     {
824         CString Token = path.Tokenize(_T("\\"), index);
825 
826         while (!Token.IsEmpty())
827         {
828             if (Token.Find(_T(":")) != -1)
829             {
830                 Token += "\\";
831             }
832             if (_tchdir(Token) == 0)
833             {
834                 Token = path.Tokenize(_T("\\"), index);
835                 if (!Token.IsEmpty())
836                 {
837                     _wmkdir(Token);
838                 }
839             }
840         }
841     }
842 }
843 
844 
845 ///////////////////////////////////////////////////////////////////////////////
GetAppDataPath()846 CString GetAppDataPath()
847 {
848     CString path = CString(getenv("APPDATA"));
849     path += "\\Eclipse Foundation\\Eclipse_ThreadX\\GUIX_Studio";
850     MakePath(path);
851     return path;
852 }
853 
854 ///////////////////////////////////////////////////////////////////////////////
CalculateStudioVersion()855 int CalculateStudioVersion()
856 {
857     int studio_version = GUIX_MAJOR_VERSION * 1000000 + GUIX_MINOR_VERSION * 10000 + GUIX_PATCH_VERSION * 100 + STUDIOX_VERSION_NUMBER;
858     return studio_version;
859 }
860 
861 
862 ///////////////////////////////////////////////////////////////////////////////
ReadIniInfo(void)863 BOOL ReadIniInfo(void)
864 {
865     int loop;
866     BOOL FoundIni = FALSE;
867 
868     /* Configure defaults in case this is first time use */
869 
870     StudioXIni.ini_version = STUDIO_INI_VERSION;
871     StudioXIni.studio_version = CalculateStudioVersion();
872     StudioXIni.first_run = 1;
873 
874     StudioXIni.xpos = 20;
875     StudioXIni.ypos = 20;
876     StudioXIni.width = 1100;
877     StudioXIni.height = 640;
878     StudioXIni.proj_view_width = 200;
879     StudioXIni.resource_view_width = 200;
880     StudioXIni.proj_view_height = 240;
881     StudioXIni.samples_dir = "";
882 
883     for (loop = 0; loop < MAX_RECENT_PROJECTS; loop++)
884     {
885         StudioXIni.recent_project_paths[loop] = "";
886     }
887 
888     CString inipath = GetAppDataPath() + "\\" + INI_FILE_NAME;
889     xml_reader reader;
890 
891     if (reader.ReadFile(inipath))
892     {
893         FoundIni = TRUE;
894 
895         if (reader.EnterSection("information"))
896         {
897             reader.ReadInt("ini_version", StudioXIni.ini_version, 1);
898             reader.ReadInt("studio_version", StudioXIni.studio_version, 0);
899             reader.ReadString("samples_dir", StudioXIni.samples_dir);
900             reader.CloseSection(TRUE, TRUE);
901         }
902 
903         // KGM we can add logic here to detect older Studio version and older
904         // INI version, if and when we need to. Then, reset version information
905         // to current version.
906 
907         if (StudioXIni.ini_version == STUDIO_INI_VERSION &&
908             StudioXIni.studio_version == CalculateStudioVersion())
909         {
910             StudioXIni.first_run = 0;
911         }
912 
913         StudioXIni.ini_version = STUDIO_INI_VERSION;
914         StudioXIni.studio_version = CalculateStudioVersion();
915 
916         if (reader.EnterSection("dimensions"))
917         {
918             reader.ReadInt("xpos", StudioXIni.xpos, 20);
919             reader.ReadInt("ypos", StudioXIni.ypos, 20);
920             reader.ReadInt("width", StudioXIni.width, 1100);
921             reader.ReadInt("height", StudioXIni.height, 640);
922             reader.ReadInt("project_width", StudioXIni.proj_view_width, 200);
923             reader.ReadInt("resource_width", StudioXIni.resource_view_width, 200);
924             reader.ReadInt("project_height", StudioXIni.proj_view_height, 240);
925             reader.CloseSection(TRUE, TRUE);
926         }
927         if (StudioXIni.width < 0)
928         {
929             StudioXIni.width = 1100;
930         }
931         if (StudioXIni.height < 0)
932         {
933             StudioXIni.height = 640;
934         }
935         if (StudioXIni.proj_view_width < 0)
936         {
937             StudioXIni.proj_view_width = 200;
938         }
939         if (StudioXIni.resource_view_width < 0)
940         {
941             StudioXIni.resource_view_width = 200;
942         }
943         if (StudioXIni.proj_view_height < 0)
944         {
945             StudioXIni.proj_view_height = 240;
946         }
947 
948         if (reader.EnterSection("recent_projects"))
949         {
950             for (loop = 0; loop < MAX_RECENT_PROJECTS; loop++)
951             {
952                 reader.ReadString("pathname", StudioXIni.recent_project_paths[loop]);
953             }
954             reader.CloseSection();
955         }
956     }
957 
958     // Check to make sure the initial position is on the screen:
959     int size = GetSystemMetrics(SM_CXVIRTUALSCREEN);
960     if (StudioXIni.xpos < 0 || StudioXIni.xpos >= size - 10)
961     {
962         StudioXIni.xpos = 20;
963     }
964 
965     size = GetSystemMetrics(SM_CYVIRTUALSCREEN);
966     if (StudioXIni.ypos < 0 || StudioXIni.ypos >= size - 10)
967     {
968         StudioXIni.ypos = 20;
969     }
970     return FoundIni;
971 }
972 
973 ///////////////////////////////////////////////////////////////////////////////
WriteIniInfo(void)974 void WriteIniInfo(void)
975 {
976     int loop;
977     xml_writer writer;
978 
979     // Let's try to read the config file:
980 
981     CString inipath = GetAppDataPath() + "\\" + INI_FILE_NAME;
982 
983     StudioXIni.ini_version = STUDIO_INI_VERSION;
984     StudioXIni.studio_version = CalculateStudioVersion();
985 
986     if (writer.OpenFile(inipath))
987     {
988         writer.OpenTag("information");
989         writer.WriteInt("ini_version", StudioXIni.ini_version);
990         writer.WriteInt("studio_version", StudioXIni.studio_version);
991         writer.WriteString("samples_dir", StudioXIni.samples_dir);
992         writer.CloseTag("information");
993 
994         writer.OpenTag("dimensions");
995         writer.WriteInt("xpos", StudioXIni.xpos);
996         writer.WriteInt("ypos", StudioXIni.ypos);
997         writer.WriteInt("width", StudioXIni.width);
998         writer.WriteInt("height", StudioXIni.height);
999         writer.WriteInt("project_width", StudioXIni.proj_view_width);
1000         writer.WriteInt("resource_width", StudioXIni.resource_view_width);
1001         writer.WriteInt("project_height", StudioXIni.proj_view_height);
1002         writer.CloseTag("dimensions");
1003 
1004         writer.OpenTag("recent_projects");
1005 
1006         for (loop = 0; loop < MAX_RECENT_PROJECTS; loop++)
1007         {
1008             if (StudioXIni.recent_project_paths[loop].IsEmpty())
1009             {
1010                 break;
1011             }
1012             else
1013             {
1014                 writer.WriteString("pathname", StudioXIni.recent_project_paths[loop]);
1015             }
1016         }
1017         writer.CloseTag("recent_projects");
1018         writer.CloseFile();
1019     }
1020 }
1021 
1022 #include "winerror.h"
1023 
1024 ///////////////////////////////////////////////////////////////////////////////
GetSamplesDir()1025 CString GetSamplesDir()
1026 {
1027     TCHAR module_path[MAX_PATH];
1028     CString pathname;
1029 
1030     if (StudioXIni.samples_dir.IsEmpty())
1031     {
1032         // test to see if we are running a local test instance:
1033         if (GetModuleFileName(NULL, module_path, MAX_PATH))
1034         {
1035             pathname = module_path;
1036             if (pathname.Find(_T("WindowsApps"), 0) == -1)
1037             {
1038                 // Not installed from App Store, so running local test.
1039                 // Added this for testing, version test might needed here.
1040                 return _T("C:\\Eclipse_ThreadX\\GUIX_Studio_test");
1041             }
1042         }
1043     }
1044     return StudioXIni.samples_dir;
1045 }
1046 
1047 ///////////////////////////////////////////////////////////////////////////////
GetStudioInstallFolder()1048 CString GetStudioInstallFolder()
1049 {
1050     CString root_path;
1051     TCHAR module_path[MAX_PATH];
1052 
1053     if (GetModuleFileName(NULL, module_path, MAX_PATH))
1054     {
1055         root_path = module_path;
1056         #if defined(_DEBUG)
1057         root_path = root_path.Left(root_path.Find(_T("\\Debug"), 0));
1058         #else
1059         if (root_path.Find(_T("\\WindowsApps") > 0))
1060         {
1061             // here if installed from App Store
1062             root_path = root_path.Left(root_path.Find(_T("\\studiox"), 0));
1063         }
1064         else
1065         {
1066             // here if running local release mode build
1067             root_path = root_path.Left(root_path.Find(_T("\\Release"), 0));
1068         }
1069         #endif
1070     }
1071     return root_path;
1072 }
1073 
1074 ///////////////////////////////////////////////////////////////////////////////
GetTestingParam(int index)1075 CString GetTestingParam(int index)
1076 {
1077     static char *fparam0 = "c:\\temp\\guix_param0.txt";
1078     static char *fparam1 = "c:\\temp\\guix_param1.txt";
1079 
1080     CString val("");
1081     size_t size;
1082     char param[MAX_PATH];
1083     char *filename;
1084     FILE *file;
1085 
1086     memset(param, 0, MAX_PATH);
1087 
1088     if (index)
1089     {
1090         filename = fparam1;
1091     }
1092     else
1093     {
1094         filename = fparam0;
1095     }
1096 
1097     file = fopen(filename, "r");
1098 
1099     if (file)
1100     {
1101         size = fread(param, 1, MAX_PATH, file);
1102 
1103         if (size)
1104         {
1105             val = CString(param);
1106         }
1107         fclose(file);
1108     }
1109     return val;
1110 }
1111 
1112 ///////////////////////////////////////////////////////////////////////////////
GetMallocName()1113 CString GetMallocName()
1114 {
1115     CString val("");
1116 
1117     if (gpOpenProject)
1118     {
1119         val = gpOpenProject->mHeader.malloc_name;
1120     }
1121     return val;
1122 }
1123 
1124 ///////////////////////////////////////////////////////////////////////////////
MoveRecentPathToFront(int index)1125 void MoveRecentPathToFront(int index)
1126 {
1127     int loop;
1128     CString temp;
1129 
1130     temp = StudioXIni.recent_project_paths[index];
1131 
1132     for (loop = index; loop > 0; loop--)
1133     {
1134         StudioXIni.recent_project_paths[loop] =
1135             StudioXIni.recent_project_paths[loop - 1];
1136     }
1137     StudioXIni.recent_project_paths[0] = temp;
1138 }
1139 
1140 
1141 ///////////////////////////////////////////////////////////////////////////////
AddRecentProject(CString & pathname)1142 void AddRecentProject(CString &pathname)
1143 {
1144     int loop;
1145 
1146     BOOL path_exist = FALSE;
1147 
1148     // if this is already in my list, just move it to the front:
1149 
1150     for (loop = 0; loop < MAX_RECENT_PROJECTS; loop++)
1151     {
1152         if (StudioXIni.recent_project_paths[loop] == pathname)
1153         {
1154             if (loop == 0)
1155             {
1156                 return;
1157             }
1158             path_exist = TRUE;
1159             MoveRecentPathToFront(loop);
1160             break;
1161         }
1162     }
1163 
1164     // the path doesn't exist, move everything down by 1 and put in front:
1165     if (!path_exist)
1166     {
1167         for (loop = MAX_RECENT_PROJECTS - 1; loop > 0; loop--)
1168         {
1169             StudioXIni.recent_project_paths[loop] =
1170                 StudioXIni.recent_project_paths[loop - 1];
1171         }
1172         StudioXIni.recent_project_paths[0] = pathname;
1173     }
1174 
1175     // update recent projects menu
1176     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
1177     pMain->UpdateRecentProjectsMenu();
1178 }
1179 
1180 ///////////////////////////////////////////////////////////////////////////////
GetProjectView()1181 project_view *GetProjectView()
1182 {
1183     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
1184     return pMain->GetProjectView();
1185 }
1186 
1187 ///////////////////////////////////////////////////////////////////////////////
GetTargetView()1188 target_view *GetTargetView()
1189 {
1190     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
1191     return pMain->GetTargetView();
1192 }
1193 
1194 ///////////////////////////////////////////////////////////////////////////////
GetTargetScreen()1195 target_screen *GetTargetScreen()
1196 {
1197     return (GetTargetView()->GetTargetScreen());
1198 }
1199 
1200 ///////////////////////////////////////////////////////////////////////////////
GetResourceView()1201 resource_view *GetResourceView()
1202 {
1203     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
1204     return pMain->GetResourceView();
1205 }
1206 
1207 ///////////////////////////////////////////////////////////////////////////////
GetPropsWin()1208 properties_win *GetPropsWin()
1209 {
1210     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
1211     return pMain->GetPropsWin();
1212 }
1213 
1214 ///////////////////////////////////////////////////////////////////////////////
GetCmdInfo()1215 CCommandInfo *GetCmdInfo()
1216 {
1217     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
1218     return pMain->GetCmdInfo();
1219 }
1220 
1221 ///////////////////////////////////////////////////////////////////////////////
UndoManager()1222 undo_manager *UndoManager()
1223 {
1224     CMainFrame *pMain = (CMainFrame *)AfxGetApp()->GetMainWnd();
1225     return pMain->GetUndoManager();
1226 }
1227 
1228 ///////////////////////////////////////////////////////////////////////////////
GetActiveStringTable()1229 string_table *GetActiveStringTable()
1230 {
1231     string_table *table = NULL;
1232 
1233     if (gpOpenProject)
1234     {
1235         int display = GetProjectView()->GetActiveDisplay();
1236 
1237         if (display >= 0 && display < gpOpenProject->mHeader.max_displays)
1238         {
1239             table = gpOpenProject->mDisplays[display].stable;
1240         }
1241     }
1242     return table;
1243 }
1244 
1245 ///////////////////////////////////////////////////////////////////////////////
GetActiveCharacterMap(BOOL reset)1246 FontCharMap *GetActiveCharacterMap(BOOL reset)
1247 {
1248     string_table *table = GetActiveStringTable();
1249     if (table)
1250     {
1251         if (reset)
1252         {
1253             table->GenerateCleanCharacterMap();
1254         }
1255         return table->GetCharacterMap();
1256     }
1257     return NULL;
1258 }
1259 
1260 ///////////////////////////////////////////////////////////////////////////////
ColorRefToGxColor(COLORREF cr)1261 GX_COLOR ColorRefToGxColor(COLORREF cr)
1262 {
1263     GX_COLOR val;
1264     BYTE red = GetRValue(cr);
1265     BYTE green = GetGValue(cr);
1266     BYTE blue = GetBValue(cr);
1267 
1268     val = red;
1269     val <<= 8;
1270     val |= green;
1271     val <<= 8;
1272     val |= blue;
1273     return val;
1274 }
1275 
1276 
1277 ///////////////////////////////////////////////////////////////////////////////
GxColorToColorRef(GX_COLOR gx)1278 COLORREF GxColorToColorRef(GX_COLOR gx)
1279 {
1280     BYTE red =   (BYTE) ((gx >> 16) & 0xff);
1281     BYTE green = (BYTE) ((gx >> 8) & 0xff);
1282     BYTE blue =  (BYTE) (gx & 0xff);
1283 
1284     return RGB(red, green, blue);
1285 }
1286 
1287 /*****************************************************************************/
IsAlphaFormat(int color_format)1288 BOOL IsAlphaFormat(int color_format)
1289 {
1290     if (color_format == GX_COLOR_FORMAT_4444ARGB ||
1291         color_format == GX_COLOR_FORMAT_32ARGB ||
1292         color_format == GX_COLOR_FORMAT_8BIT_ALPHAMAP)
1293     {
1294         return TRUE;
1295     }
1296     return FALSE;
1297 }
1298 
1299 /*****************************************************************************/
IsCpuWithDave2D(int cpu_type)1300 BOOL IsCpuWithDave2D(int cpu_type) // does the CPU support Dave2D?
1301 {
1302     if (cpu_type == CPU_SYNERGY ||
1303         cpu_type == CPU_RA ||
1304         cpu_type == CPU_RX)
1305     {
1306         return TRUE;
1307     }
1308     return FALSE;
1309 }
1310 
1311 /*****************************************************************************/
IsCpuWithDave2D(studiox_project * project)1312 BOOL IsCpuWithDave2D(studiox_project *project)                        // does the CPU support Dave2D?
1313 {
1314     return IsCpuWithDave2D(project->mHeader.target_cpu);
1315 }
1316 
1317 ///////////////////////////////////////////////////////////////////////////////
IsRenesasDave2D(studiox_project * project)1318 BOOL IsRenesasDave2D(studiox_project *project)      // Is the project configured with Dave2D enabled?
1319 {
1320     if (project)
1321     {
1322         if (IsCpuWithDave2D(project))
1323         {
1324             if (project->mHeader.dave2d_graph_accelerator)
1325             {
1326                 return TRUE;
1327             }
1328         }
1329     }
1330     return FALSE;
1331 }
1332 
1333 ///////////////////////////////////////////////////////////////////////////////
IsDave2dFontFormat(studiox_project * project,int display)1334 BOOL IsDave2dFontFormat(studiox_project* project, int display)
1335 {
1336     if (project && IsRenesasDave2D(project))
1337     {
1338         switch (project->mDisplays[display].colorformat)
1339         {
1340         case GX_COLOR_FORMAT_8BIT_PALETTE:
1341             if (project_lib_version() >= GX_VERSION_SYNERGY_GLYPH_GEN_CHANGE)
1342             {
1343                 // Generate GUIX version glyph data for 8bpp palette mode.
1344                 return FALSE;
1345             }
1346             break;
1347         }
1348 
1349         return TRUE;
1350     }
1351 
1352     return FALSE;
1353 }
1354 
1355 
1356 ///////////////////////////////////////////////////////////////////////////////
IsSTChromeArt(studiox_project * project)1357 BOOL IsSTChromeArt(studiox_project *project)
1358 {
1359     if (project && (project->mHeader.target_cpu == CPU_ST_CHROMEART))
1360     {
1361         return TRUE;
1362     }
1363 
1364     return FALSE;
1365 }
1366 
1367 
1368 ///////////////////////////////////////////////////////////////////////////////
IsRenesasHwJpeg(studiox_project * project)1369 BOOL IsRenesasHwJpeg(studiox_project *project)
1370 {
1371     if (project->mHeader.target_cpu == CPU_SYNERGY ||
1372         project->mHeader.target_cpu == CPU_RA)
1373     {
1374         if (project->mHeader.renesas_jpeg_decoder == DECODER_TYPE_HW)
1375         {
1376             return TRUE;
1377         }
1378     }
1379     return FALSE;
1380 }
1381 
1382 ///////////////////////////////////////////////////////////////////////////////
pixelmap_destroy(GX_PIXELMAP * map)1383 void pixelmap_destroy(GX_PIXELMAP *map)
1384 {
1385     if (map->gx_pixelmap_data)
1386     {
1387         delete [] map->gx_pixelmap_data;
1388         map->gx_pixelmap_data = NULL;
1389     }
1390     if (map->gx_pixelmap_aux_data)
1391     {
1392         // The pixelmap aux data can point at a shared palette, but in that case
1393         // we give each pixelmap it's own copy of the shared palette, so we don't
1394         // run into issues of deleting the same color array multiple times.
1395         delete map->gx_pixelmap_aux_data;
1396         map->gx_pixelmap_aux_data = NULL;
1397     }
1398     delete map;
1399 }
1400 
1401 ///////////////////////////////////////////////////////////////////////////////
pixelmap_list_destroy(CArray<GX_PIXELMAP * > & pixelmap_list)1402 void pixelmap_list_destroy(CArray<GX_PIXELMAP *> &pixelmap_list)
1403 {
1404     GX_PIXELMAP *map;
1405 
1406     for (int index = 0; index < pixelmap_list.GetCount(); index++)
1407     {
1408         map = pixelmap_list.GetAt(index);
1409 
1410         if (map)
1411         {
1412             pixelmap_destroy(map);
1413         }
1414     }
1415 
1416     pixelmap_list.RemoveAll();
1417 }
1418 
1419 
1420 ///////////////////////////////////////////////////////////////////////////////
PaintBmp(CDC * dc,int x,int y,int icon_id)1421 void PaintBmp(CDC *dc, int x, int y, int icon_id)
1422 {
1423     CBitmap map;
1424     BITMAP  bmp;
1425 
1426     if (map.LoadBitmap(icon_id))
1427     {
1428         map.GetBitmap(&bmp);
1429 
1430         CDC dcMemory;
1431         dcMemory.CreateCompatibleDC(dc);
1432         dcMemory.SelectObject(&map);
1433 
1434         int dpi = GetSystemDPI();
1435         int width = MulDiv(bmp.bmWidth, dpi, DEFAULT_DPI_96);
1436         int height = MulDiv(bmp.bmHeight, dpi, DEFAULT_DPI_96);
1437         dc->StretchBlt(x, y, width, height, &dcMemory,0, 0, bmp.bmWidth, bmp.bmHeight, SRCCOPY);
1438     }
1439 }
1440 
1441 ///////////////////////////////////////////////////////////////////////////////
FontCharMap()1442 FontCharMap::FontCharMap()
1443 {
1444     map_size = 8192;
1445     map = new unsigned char[8192];
1446     Clear();
1447 }
1448 
1449 
1450 ///////////////////////////////////////////////////////////////////////////////
~FontCharMap()1451 FontCharMap::~FontCharMap()
1452 {
1453     delete [] map;
1454 }
1455 
1456 ///////////////////////////////////////////////////////////////////////////////
Test(DWORD val)1457 BOOL FontCharMap::Test(DWORD val)
1458 {
1459     DWORD index = val >> 3;
1460     unsigned char mask = 0x80 >> (val & 7);
1461 
1462     if (index < map_size)
1463     {
1464         if (map[index] & mask)
1465         {
1466             return TRUE;
1467         }
1468     }
1469     return FALSE;
1470 }
1471 
1472 ///////////////////////////////////////////////////////////////////////////////
Test(DWORD start,DWORD end)1473 BOOL FontCharMap::Test(DWORD start, DWORD end)
1474 {
1475     while(start <= end)
1476     {
1477         if (Test(start))
1478         {
1479             return TRUE;
1480         }
1481         start++;
1482     }
1483     return FALSE;
1484 }
1485 
1486 ///////////////////////////////////////////////////////////////////////////////
Set(DWORD val)1487 void FontCharMap::Set(DWORD val)
1488 {
1489     DWORD index = val >> 3;
1490     if (index < map_size)
1491     {
1492         unsigned char mask = 0x80 >> (val & 7);
1493         map[index] |= mask;
1494     }
1495 }
1496 
1497 ///////////////////////////////////////////////////////////////////////////////
Set(DWORD start,DWORD end)1498 void FontCharMap::Set(DWORD start, DWORD end)
1499 {
1500     while(start <= end)
1501     {
1502         Set(start);
1503         start++;
1504     }
1505 }
1506 
1507 ///////////////////////////////////////////////////////////////////////////////
TestAndSet(DWORD val)1508 BOOL FontCharMap::TestAndSet(DWORD val)
1509 {
1510     if (Test(val))
1511     {
1512         return FALSE;
1513     }
1514     Set(val);
1515     return TRUE;
1516 }
1517 
1518 ///////////////////////////////////////////////////////////////////////////////
SetMapSize(ULONG size)1519 void FontCharMap::SetMapSize(ULONG size)
1520 {
1521     if (map_size != size)
1522     {
1523         if (map)
1524         {
1525             delete[] map;
1526         }
1527 
1528         map_size = size;
1529         map = new unsigned char[map_size];
1530         Clear();
1531     }
1532 }
1533 
1534 ///////////////////////////////////////////////////////////////////////////////
Clear()1535 void FontCharMap::Clear()
1536 {
1537     memset(map, 0, map_size);
1538 }
1539 
1540 ///////////////////////////////////////////////////////////////////////////////
AddToMap(CString & val)1541 BOOL FontCharMap::AddToMap(CString &val)
1542 {
1543     BOOL new_char = FALSE;
1544     if (val.IsEmpty())
1545     {
1546         return FALSE;
1547     }
1548 
1549 #ifdef _UNICODE
1550     wchar_t *wide_text = (wchar_t *)val.GetString();
1551 #else
1552     wchar_t *wide_text = CStringToWideChar(val);
1553 #endif
1554 
1555     if (wide_text)
1556     {
1557         wchar_t *get = wide_text;
1558         DWORD unicode;
1559 
1560         while(*get)
1561         {
1562             if (((*get) >= 0xd800) && ((*get) <= 0xdbff))
1563             {
1564                 //Unicode from 0x10000 to 0x10ffff are encoded as two 16-bit code units called surrogate pairs
1565                 //recombine the surrogate pairs to get a 4 byte unicode
1566                 unicode = (*get) & (~0xd800);
1567                 unicode <<= 10;
1568                 unicode += 0x10000;
1569 
1570                 get++;
1571                 unicode += (*get) & (~0xdc00);
1572 
1573                 if (map_size != CHARMAP_SIZE_EXTENDED)
1574                 {
1575                     unsigned char *new_map = new unsigned char[CHARMAP_SIZE_EXTENDED];
1576                     memset(new_map, 0, CHARMAP_SIZE_EXTENDED);
1577                     memcpy_s(new_map, CHARMAP_SIZE_EXTENDED, map, CHARMAP_SIZE_DEFAULT);
1578                     delete[]map;
1579                     map = new_map;
1580                     map_size = CHARMAP_SIZE_EXTENDED;
1581                 }
1582             }
1583             else
1584             {
1585                 unicode = *get;
1586             }
1587 
1588             if ((unicode >= 0x20) && TestAndSet(unicode))
1589             {
1590                 new_char = TRUE;
1591             }
1592             get++;
1593         }
1594 #ifndef _UNICODE
1595         delete [] wide_text;
1596 #endif
1597     }
1598     return new_char;
1599 }
1600 
1601 ///////////////////////////////////////////////////////////////////////////////
Overlay(FontCharMap * other)1602 void FontCharMap::Overlay(FontCharMap *other)
1603 {
1604     DWORD val;
1605     DWORD maxval = GetMapSize() << 3;
1606 
1607     if (!other)
1608     {
1609         return;
1610     }
1611 
1612     for (val = 0; val < maxval; val++)
1613     {
1614         if (other->Test(val))
1615         {
1616             Set(val);
1617         }
1618     }
1619 }
1620 
1621 ///////////////////////////////////////////////////////////////////////////////
IsEmpty()1622 BOOL FontCharMap::IsEmpty()
1623 {
1624     DWORD val;
1625     DWORD maxval = GetMapSize() << 3;
1626 
1627     for (val = 0; val < maxval; val++)
1628     {
1629         if (Test(val))
1630         {
1631             return FALSE;
1632         }
1633     }
1634     return TRUE;
1635 }
1636 
1637 //////////////////////////////////////////////////////////////////////////////
NumberFormatWithCommas(long value)1638 CString NumberFormatWithCommas(long value)
1639 {
1640     // Format a number with commas.
1641     CString str;
1642     int insert_pos;
1643 
1644     str.Format(_T("%d"), value);
1645 
1646     insert_pos = str.GetLength() - 3;
1647     value /= 1000;
1648 
1649     while (value)
1650     {
1651         str.Insert(insert_pos, _T(","));
1652         value /= 1000;
1653         insert_pos -= 4;
1654     }
1655 
1656     return str;
1657 }
1658 
1659 ///////////////////////////////////////////////////////////////////////////////
FormatPath(CString & path)1660 VOID FormatPath(CString &path)
1661 {
1662 
1663     path.Replace('/', '\\');
1664     path = path.TrimLeft(_T("\\"));
1665 }
1666 
1667 ///////////////////////////////////////////////////////////////////////////////
1668 /*Check file exists or not.*/
FileExists(INT pathtype,CString pathname)1669 BOOL FileExists(INT pathtype, CString pathname)
1670 {
1671     CString file = pathname;
1672     PATHINFO path_info;
1673     path_info.pathname = pathname;
1674 
1675     switch (pathtype)
1676     {
1677     case PATH_TYPE_INSTALL_RELATIVE:
1678     case PATH_TYPE_PROJECT_RELATIVE:
1679         path_info.pathtype = pathtype;
1680         file = MakeAbsolutePathname(path_info);
1681         break;
1682 
1683     case PATH_TYPE_ABSOLUTE:
1684     default:
1685         break;
1686     }
1687 
1688     if (GetFileAttributes(file) == INVALID_FILE_ATTRIBUTES)
1689     {
1690         /*file does not exists*/
1691         return false;
1692     }
1693 
1694     return true;
1695 }
1696 
1697 ///////////////////////////////////////////////////////////////////////////////
FileExists(INT display_index,INT resource_type,CString pathname)1698 BOOL FileExists(INT display_index, INT resource_type, CString pathname)
1699 {
1700     /*We should check the name in whole group, not just in current folder.
1701     So we must find the group forst.*/
1702     INT group_id;
1703     res_info* group_info = NULL;
1704 
1705     switch (resource_type)
1706     {
1707     case RES_TYPE_COLOR:
1708         group_id = COLOR_GROUP;
1709         break;
1710 
1711     case RES_TYPE_FONT:
1712         group_id = FONT_GROUP;
1713         break;
1714 
1715     case RES_TYPE_PIXELMAP:
1716         group_id = PIXELMAP_GROUP;
1717         break;
1718 
1719     case RES_TYPE_STRING:
1720         group_id = STRING_GROUP;
1721         break;
1722 
1723     default:
1724         return FALSE;
1725     }
1726 
1727     studiox_project *project = GetOpenProject();
1728     int active_theme = project->mDisplays[display_index].active_theme;
1729     group_info = project->FindResource(display_index, active_theme, RES_TYPE_GROUP, group_id);
1730 
1731     // Detemin whether the specified file exist
1732     CString str;
1733     res_info *child_folder = group_info->child;
1734     res_info* child = child_folder->child;
1735 
1736     FormatPath(pathname);
1737     ConvertToProjectRelativePath(pathname);
1738     while (child_folder && (child_folder->type == RES_TYPE_FOLDER))
1739     {
1740         child = child_folder->child;
1741         while (child)
1742         {
1743             if (child->type == resource_type)
1744             {
1745                 str = MakeAbsolutePathname(child->pathinfo);
1746                 ConvertToProjectRelativePath(str);
1747                 FormatPath(str);
1748 
1749                 if (_tcscmp(str, pathname) == 0)
1750                 {
1751                     return TRUE;
1752                 }
1753             }
1754 
1755             child = child->next;
1756         }
1757         child_folder = child_folder->next;
1758     }
1759 
1760     return FALSE;
1761 }
1762 
1763 ///////////////////////////////////////////////////////////////////////////////
NameExists(INT display_index,INT resource_type,CString name)1764 BOOL NameExists(INT display_index, INT resource_type, CString name)
1765 {
1766     /*We should check the name in whole group, not just in current folder.
1767     So we must find the group forst.*/
1768     /*We want use this function for all name check. But font doesn't be added to its parent group while
1769     do this check. So we need to find the group.*/
1770     INT group_id;
1771     res_info* group_info = NULL;
1772 
1773     switch (resource_type)
1774     {
1775     case RES_TYPE_COLOR:
1776         group_id = COLOR_GROUP;
1777         break;
1778 
1779     case RES_TYPE_FONT:
1780         group_id = FONT_GROUP;
1781         break;
1782 
1783     case RES_TYPE_PIXELMAP:
1784         group_id = PIXELMAP_GROUP;
1785         break;
1786 
1787     case RES_TYPE_STRING:
1788         group_id = STRING_GROUP;
1789         break;
1790 
1791     default:
1792         return FALSE;
1793     }
1794 
1795     studiox_project *project = GetOpenProject();
1796     int active_theme = project->mDisplays[display_index].active_theme;
1797     group_info = project->FindResource(display_index, active_theme, RES_TYPE_GROUP, group_id);
1798 
1799     if (group_info == NULL)
1800     {
1801         return FALSE;
1802     }
1803 
1804     res_info *child_folder = group_info -> child;
1805     res_info* child = child_folder -> child;
1806     CString child_name;
1807     CString name_suffix;
1808     int size;
1809 
1810     name.MakeUpper();
1811 
1812     /*Traverse all folder to compare the name.*/
1813     while (child_folder && (child_folder->type == RES_TYPE_FOLDER))
1814     {
1815         child = child_folder->child;
1816         while (child)
1817         {
1818 
1819             if (child->type == resource_type)
1820             {
1821                 if ((resource_type == RES_TYPE_PIXELMAP) && (child->map_list.GetCount() > 1))
1822                 {
1823                     // [resource name][_F][numbers] name pattern is reserved for frame names of multi-frame image.
1824 
1825                     child_name.Format(_T("%s_F"), child->name);
1826                     child_name.MakeUpper();
1827                     size = child_name.GetLength();
1828                     if (name.GetLength() > child_name.GetLength())
1829                     {
1830                         name_suffix = name.Mid(size);
1831 
1832                         if ((name.Left(size) == child_name) && (name_suffix.SpanIncluding(L"0123456789") == name_suffix))
1833                         {
1834                             return TRUE;
1835                         }
1836                     }
1837                 }
1838 
1839                 child_name = child->name;
1840                 child_name.MakeUpper();
1841 
1842                 if (_tcscmp(child_name, name) == 0)
1843                 {
1844                     return TRUE;
1845                 }
1846             }
1847 
1848             child = child->next;
1849         }
1850         child_folder = child_folder->next;
1851     }
1852 
1853     return FALSE;
1854 }
1855 
1856 
1857 //////////////////////////////////////////////////////////////////////////////
GetSubMenuIndex(CMenu * pMenu,CString string)1858 INT GetSubMenuIndex(CMenu *pMenu, CString string)
1859 {
1860     // find a submenu according to string
1861     CString get_string;
1862 
1863     for (int index = 0; index < pMenu->GetMenuItemCount(); index++)
1864     {
1865         pMenu->GetMenuString(index, get_string, MF_BYPOSITION);
1866         if (!get_string.Compare(string))
1867         {
1868             return index;
1869         }
1870     }
1871 
1872     return -1;
1873 }
1874 
1875 ///////////////////////////////////////////////////////////////////////////////
GetSubMenuIndex(CMenu * pMenu,INT id)1876 INT GetSubMenuIndex(CMenu *pMenu, INT id)
1877 {
1878     for (int index = 0; index < pMenu->GetMenuItemCount(); index++)
1879     {
1880         if (pMenu->GetMenuItemID(index) == id)
1881         {
1882             return index;
1883         }
1884     }
1885 
1886     return -1;
1887 }
1888 
1889 /////////////////////////////////////////////////////////////////////////////
SplitString(CString str,CHAR splitter,CStringArray * list)1890 void SplitString(CString str, CHAR splitter, CStringArray *list)
1891 {
1892     int index = str.Find(splitter);
1893 
1894     while (index >= 0)
1895     {
1896         list->Add(str.Left(index));
1897 
1898         str = str.Mid(index + 1);
1899         index = str.Find(splitter);
1900     }
1901 
1902     list->Add(str);
1903 }
1904 
1905 /////////////////////////////////////////////////////////////////////////////
GetSystemDPI()1906 int GetSystemDPI()
1907 {
1908     // get DPI for the system
1909     HDC hdc = ::GetDC(NULL);
1910 
1911     int dpi = GetDeviceCaps(hdc, LOGPIXELSX);
1912 
1913     ::ReleaseDC(NULL, hdc);
1914 
1915     return dpi;
1916 }
1917 
1918 //////////////////////////////////////////////////////////////////////////////
GuixVersionFieldsToVersionNumber(int major,int minor,int service_pack)1919 int GuixVersionFieldsToVersionNumber(int major, int minor, int service_pack)
1920 {
1921     int version_number = (major * 10000) + (minor * 100) + service_pack;
1922     return version_number;
1923 }
1924 
GuixVersionNumberToVersionFields(int version_number,int & major,int & minor,int & service_pack)1925 void GuixVersionNumberToVersionFields(int version_number, int &major, int &minor, int &service_pack)
1926 {
1927     major = version_number / 10000;
1928     version_number -= major * 10000;
1929     minor = version_number / 100;
1930     version_number -= minor * 100;
1931     service_pack = version_number;
1932 }
1933 
1934 //////////////////////////////////////////////////////////////////////////////
1935 /*Return false when the check doesn't pass.*/
TestInputName(CString & input_string,char * field_name,CWnd * parent,BOOL show_error_message)1936 BOOL TestInputName(CString &input_string, char *field_name, CWnd *parent, BOOL show_error_message)
1937 {
1938     INT index = 1;
1939     TCHAR temp_char;
1940     char msg[256];
1941 
1942     if (input_string.IsEmpty())
1943     {
1944         if (show_error_message)
1945         {
1946             sprintf_s(msg, sizeof(msg), "The \"%s\" field cannot be empty.", field_name);
1947             Notify(msg, parent);
1948         }
1949         return false;
1950     }
1951 
1952     BOOL meet_naming_rule = TRUE;
1953 
1954     temp_char = input_string[0];
1955 
1956     /*Input name must start with alpha or underline.*/
1957 
1958     if (!(isalpha(temp_char)) && (temp_char != '_'))
1959     {
1960         meet_naming_rule = FALSE;
1961     }
1962     else
1963     {
1964         /*Component ID must be consisted of liters, number and '_'.*/
1965         while (input_string[index])
1966         {
1967             temp_char = input_string.GetAt(index);
1968 
1969             /*Is this character a num? liter? or '_'? */
1970             if ((temp_char >= 0) && (temp_char <= 255) && (isalnum(temp_char) || (temp_char == '_')))
1971             {
1972                 index++;
1973             }
1974             else
1975             {
1976                 meet_naming_rule = FALSE;
1977                 break;;
1978             }
1979         }
1980     }
1981 
1982     if (!meet_naming_rule)
1983     {
1984         if (show_error_message)
1985         {
1986             sprintf_s(msg, sizeof(msg), "The \"%s\" field must meet ANSI C variable naming rules.", field_name);
1987             Notify(msg, parent);
1988         }
1989         return false;
1990     }
1991     return true;
1992 }
1993 
1994 //////////////////////////////////////////////////////////////////////////////
1995 /*Return false when the check doesn't pass.*/
TestInputName(CEdit * input_field,char * field_name,CString & original_string,CWnd * parent)1996 BOOL TestInputName(CEdit *input_field, char *field_name, CString &original_string, CWnd *parent)
1997 {
1998     CString input_string;
1999 
2000     input_field -> GetWindowText(input_string);
2001 
2002     if(TestInputName(input_string, field_name, parent))
2003     {
2004         original_string = input_string;
2005         return TRUE;
2006     }
2007     return FALSE;
2008 }
2009 
2010 
2011 //////////////////////////////////////////////////////////////////////////////
2012 /* This function just check the import pixelmap name for now. */
SetImportIdName(INT display_index,CString & input_name)2013 BOOL SetImportIdName(INT display_index, CString &input_name)
2014 {
2015     TCHAR temp_char;
2016     INT   index = 1;
2017     CString output_name = input_name;
2018     CHAR temp_str[10];
2019     BOOL status = TRUE;
2020 
2021     if (output_name.IsEmpty())
2022     {
2023         Notify("The name is empty, please check.");
2024         return FALSE;
2025     }
2026 
2027     temp_char = input_name.GetAt(0);
2028     if (!isalpha(temp_char) && (temp_char != '_'))
2029     {
2030         /*If filename isn't started with alpha or underline. Force the first character to be underline.*/
2031         input_name.SetAt(0, '_');
2032         status = FALSE;
2033     }
2034 
2035     while (input_name[index])
2036     {
2037         temp_char = input_name.GetAt(index);
2038         /*Is this character a num? liter? or '_'? */
2039         if (!isalnum(temp_char) && (temp_char != '_'))
2040         {
2041             input_name.SetAt(index, '_');
2042             status = FALSE;
2043         }
2044         index++;
2045     }
2046 
2047     /*User may add same name file for different purpose, or different files have the same name.
2048       So set them different Id name.*/
2049     index = 1;
2050     output_name = input_name;
2051     while (NameExists(display_index, RES_TYPE_PIXELMAP, output_name))
2052     {
2053         sprintf_s(temp_str, sizeof(temp_str), "_%d", index++);
2054         output_name = input_name + CString(temp_str);
2055     }
2056 
2057     if (input_name != output_name)
2058     {
2059         input_name = output_name;
2060         /*I don't know whether the message should be shown or not. So comment it now.*/
2061         /*
2062         CString temp_msg("Image ID already exists. It will be set as ");
2063         temp_msg += input_name;
2064         Notify(CW2A(temp_msg) + ".");
2065         */
2066         status = FALSE;
2067     }
2068 
2069     return status;
2070 }
2071 
2072 
2073 //////////////////////////////////////////////////////////////////////////////
2074 /* Check file name .*/
IsFileNameFormat(CString filename)2075 BOOL IsFileNameFormat(CString filename)
2076 {
2077     int index = 0;
2078     TCHAR temp_char;
2079 
2080     if (filename.IsEmpty())
2081     {
2082         return TRUE;
2083     }
2084 
2085     /*Component ID must be consisted of liters, number and '_'.*/
2086     while (filename[index])
2087     {
2088         temp_char = filename.GetAt(index);
2089         /*Is this character a num? liter? blank space? or '_'? */
2090         if (isalnum(temp_char) || (temp_char == '_') || (temp_char == ' ') || (temp_char == '.'))
2091         {
2092             index++;
2093         }
2094         else
2095         {
2096             Notify("The output name should match file naming conventions.");
2097             return FALSE;
2098         }
2099     }
2100 
2101     return TRUE;
2102 }
2103 
2104 ////////////////////////////////////////////////////////////////////////////////////////////////
MakePixelmapName(res_info * info,int res_index)2105 CString MakePixelmapName(res_info* info, int res_index)
2106 {
2107     CString name;
2108 
2109     if (info->map_list.GetCount() > 1)
2110     {
2111         name.Format(_T("%s_F%d"), info->name, res_index);
2112     }
2113     else
2114     {
2115         name = info->name;
2116     }
2117 
2118     return name;
2119 }
2120 
2121 ////////////////////////////////////////////////////////////////////////////////////////////////
GetTextScaler()2122 ULONG GetTextScaler()
2123 {
2124     DWORD type, size;
2125     ULONG scaler = DEFAULT_TEXT_SCALER;
2126 
2127     HKEY key;
2128     RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Accessibility", 0, READ_CONTROL | KEY_QUERY_VALUE, &key);
2129 
2130     if (key)
2131     {
2132         size = sizeof(ULONG);
2133         RegQueryValueEx(key, L"TextScaleFactor", 0, &type, (BYTE*)&scaler, &size);
2134         RegCloseKey(key);
2135     }
2136 
2137     return scaler;
2138 }
2139 
2140 /////////////////////////////////////////////////////////////////////////////////////////////////
GetScaledValue(int value,int dpi,int text_scaler)2141 int GetScaledValue(int value, int dpi, int text_scaler)
2142 {
2143     // Scale the input value according to dpi and text scaler.
2144     value = MulDiv(value, dpi, DEFAULT_DPI_96);
2145     value = MulDiv(value, text_scaler, DEFAULT_TEXT_SCALER);
2146 
2147     return value;
2148 }
2149 
2150 ////////////////////////////////////////////////////////////////////////////////////////////////
ToUByte(INT value)2151 GX_UBYTE ToUByte(INT value)
2152 {
2153     if (value > 255)
2154     {
2155         return 255;
2156     }
2157     else if (value < 0)
2158     {
2159         return 0;
2160     }
2161 
2162     return value;
2163 }
2164 
2165 ///////////////////////////////////////////////////////////////////////////////
FindPairVal(STRING_VAL_PAIR * entry,CString name)2166 int FindPairVal(STRING_VAL_PAIR *entry, CString name)
2167 {
2168     while (!entry->name.IsEmpty())
2169     {
2170         if (entry->name == name)
2171         {
2172             return entry->val;
2173         }
2174 
2175         entry++;
2176     }
2177 
2178     return 0;
2179 }
2180 
2181 ///////////////////////////////////////////////////////////////////////////////
FindPairString(STRING_VAL_PAIR * entry,int val)2182 CString FindPairString(STRING_VAL_PAIR *entry, int val)
2183 {
2184     while (!entry->name.IsEmpty())
2185     {
2186         if (entry->val == val)
2187         {
2188             return entry->name;
2189         }
2190         entry++;
2191     }
2192 
2193     return L"";
2194 }