Esempio n. 1
0
File: main.c Progetto: ExAcler/Prizm
void Save_Config(const char* fn,int n)
{
    /*
	    存储分页及书签配置
		参数说明:
		    fn: 当前打开文件的文件名
		    n: 已缓存页数
	*/

    char tmp[64];
	FONTCHARACTER fname[64];
	int handle,size=0;

    memset(tmp,0,sizeof(tmp));
	strncpy(tmp,fn,strlen(fn)-strlen(strrchr(fn,'.')));    // 取文件名部分
	strcat(tmp,".cfg");
	
	char_to_font(tmp,fname);
	Bfile_CreateEntry_OS(fname,1,&size);    // 创建 .cfg 文件
	handle=Bfile_OpenFile_OS(fname,2);
	if (handle<=0) return;
	
	Bfile_WriteFile_OS(handle,&n,4);    // 前 4 字节,写入已缓存页数
	
	Bfile_SeekFile_OS(handle,4);
	Bfile_WriteFile_OS(handle,bookmark,16);    // 4*4 字节,写入书签指向的页数
	
	Bfile_SeekFile_OS(handle,20);
	Bfile_WriteFile_OS(handle,bytes,n*4);    // 4*n 字节,写入页面缓存
	Bfile_CloseFile_OS(handle);
}
Esempio n. 2
0
File: main.c Progetto: ExAcler/Prizm
void Read_Config(const char* fn,int* n)
{
    /*
	    读取分页及书签配置
		参数说明:
		    fn: 当前打开文件的文件名
		    n: 接受已缓存页数的缓冲区
	*/

    char tmp[64];
	FONTCHARACTER fname[64];
	int handle,_n=*n;

    memset(tmp,0,sizeof(tmp));
	strncpy(tmp,fn,strlen(fn)-strlen(strrchr(fn,'.')));    // 取文件名部分
	strcat(tmp,".cfg");
	
	char_to_font(tmp,fname);
	handle=Bfile_OpenFile_OS(fname,0);
	*n=_n;
	if (handle<=0) return;
	Bfile_ReadFile_OS(handle,&_n,4,0);*n=_n-1;    // 读入已缓存页数
	Bfile_ReadFile_OS(handle,bookmark,16,4);    // 读入书签页码
	Bfile_ReadFile_OS(handle,bytes,_n*4,20);    //读入页面缓存
	
	Bfile_CloseFile_OS(handle);
}
Esempio n. 3
0
void run_script(char* filename) {
  unsigned short pFile[MAX_FILENAME_SIZE+1];
  Bfile_StrToName_ncpy(pFile, (unsigned char*)filename, strlen(filename)+1); 
  int hFile = Bfile_OpenFile_OS(pFile, READWRITE, 0); // Get handle
  
  // Check for file existence
  if(hFile >= 0) // Check if it opened
  {
    // Returned no error, file exists, open it
    int size = Bfile_GetFileSize_OS(hFile);
    // File exists and has size 'size'
    // Read file into a buffer
    if ((unsigned int)size > MAX_TEXTVIEWER_FILESIZE) {
      Bfile_CloseFile_OS(hFile);
      printf("Stop: script too big\n");
      return; //file too big, return
    }
    unsigned char* asrc = (unsigned char*)alloca(size*sizeof(unsigned char)+5); // 5 more bytes to make sure it fits...
    memset(asrc, size+5, 0); //alloca does not clear the allocated space. Make sure the string is null-terminated this way.
    int rsize = Bfile_ReadFile_OS(hFile, asrc, size, 0);
    Bfile_CloseFile_OS(hFile); //we got file contents, close it
    asrc[rsize]='\0';
    execution_in_progress = 1;
    run((char*)asrc);
    execution_in_progress = 0;
  }
}
Esempio n. 4
0
FONTFILE * open_font(const char * cfname)
{
	int			fh,r;
	FONTFILE	*ff;
	fontc		ffname[32];

	char_to_font(cfname,ffname);

	fh = Bfile_OpenFile_OS(ffname,0);

	if (fh<=0) return NULL;

	ff			 		= (FONTFILE*)malloc(sizeof(FONTFILE));
	Bfile_ReadFile_OS (fh,ff,sizeof(FONTFILE)-2*sizeof(int),0);

	ff->file_handle		= fh;

	ff->width			= x86_dword_to_sh(ff->width);
	ff->height			= x86_dword_to_sh(ff->height);	
	ff->asc_offset		= x86_dword_to_sh(ff->asc_offset);
	ff->chs_offset		= x86_dword_to_sh(ff->chs_offset);

	r					=ff->width/8 + (ff->width % 8 ? 1 : 0);

	ff->font_size		= r*ff->height;

	return ff;
}
Esempio n. 5
0
File: main.c Progetto: ExAcler/Prizm
int check_consistency()
{
    /*
	    检查文件一致性,若文件有缺失则显示错误信息
	*/

    FONTCHARACTER fname[64];
	int handle,i;
	char_to_font("\\\\fls0\\24PX.hzk",fname);
    handle=Bfile_OpenFile_OS(fname,0);
	if (handle<0) return 0;
	Bfile_CloseFile_OS(handle);
	
	return 1;
}
Esempio n. 6
0
int open(const char * name,int flags,...){
	if(strcmp(name,"/dev/urandom")==0){
		sys_srand(RTC_GetTicks());
		return urandom_FD;
	}else if(strcmp(name,"/dev/fb0")==0){
		LCDstatefd=(unsigned char *)0xA8000000;
		return frameBuf_FD;
	}else{
		//Display message on screen informing user that file does not exists
		int sysmode = 0;
		if (flags==O_RDONLY) {
			sysmode = SYSFILE_MODE_READ;
		/*} else if (flags==O_WRONLY) {
			sysmode = SYSFILE_MODE_WRITE;
		} else if (flags==O_RDWR) {
			sysmode = SYSFILE_MODE_READWRITE;*/
		} else {
			fprintf(stderr,"Flag combination %d not yet supported\n",flags);
			return -1;
		}
		// Convert string to system native
		size_t plen = strlen(name);
		// We have several potential exits, so alloca simplifies ensuring this
		// gets freed (an early revision of the following logic had memory leaks).
		unsigned short *chars16 = alloca(2 * (plen + 1));
		if (chars16 == NULL) {
			errno = ENOMEM;
			return -1;
		}
		// Get a handle from the system
		Bfile_StrToName_ncpy(chars16, name, plen);
		int syshandle = Bfile_OpenFile_OS(chars16, sysmode, 0);
		if(syshandle>0)
			return fromNativeFD(syshandle);
		else
			return -1;
	}
}
Esempio n. 7
0
FILE *fopen(const char *path, const char *mode) {
    // Resolve mode
    int sysmode = 0;
    if (mode[0] == 'r') {
        sysmode = SYSFILE_MODE_READ;
    } else if (mode[0] == 'w' || mode[0] == 'a') { 
        sysmode = SYSFILE_MODE_WRITE;
    } else if (strchr(mode, '+')) {
        sysmode = SYSFILE_MODE_READWRITE;
    } else {
        errno = EINVAL;
        return NULL;
    }

    // Convert string to system native
    size_t plen = strlen(path);
    // We have several potential exits, so alloca simplifies ensuring this
    // gets freed (an early revision of the following logic had memory leaks).
    unsigned short *chars16 = alloca(2 * (plen + 1));
    if (chars16 == NULL) {
        errno = ENOMEM;
        return NULL;
    }

    // Get a handle from the system
    Bfile_StrToName_ncpy(chars16, path, plen+1);
    int syshandle = Bfile_OpenFile_OS(chars16, sysmode, 0);

    if (syshandle < 0) {
        if (sysmode == SYSFILE_MODE_WRITE ||
            sysmode == SYSFILE_MODE_READWRITE) {
            // Doesn't exist, want to write. Create.
            // FIXME Size 0 doesn't work?
            size_t size = 10;
            switch (Bfile_CreateEntry_OS(chars16, CREATEMODE_FILE, &size)) {
            case 0:
                // Success. Open file.
                syshandle = Bfile_OpenFile_OS(chars16, sysmode, 0);
                break;
            case -13:
                errno = EEXIST;
                return NULL;
            case -3:
                errno = ENOENT;
                return NULL;
            default:
                errno = EIO;
                return NULL;
            }
        } else {
            // Doesn't exist for reading.
            errno = ENOENT;
            return NULL;
        }
    }

    if (mode[0] == 'a') {
        // TODO Need to seek to end and do some junk.
        errno = ENOTIMPL;
        return NULL;
    }

    // Create a FILE and fill it in
    FILE *f = sys_malloc(sizeof(FILE));
    if (f == NULL) {
        errno = ENOMEM;
        return NULL;
    }
    memset(f, 0, sizeof(FILE));
    f->fileno = syshandle + 3;
    return f;
}
Esempio n. 8
0
File: main.c Progetto: ExAcler/Prizm
void browse_main()
{
    /*
	    文件浏览器主函数
	*/

    char ncat[64], workdir[64] = "\\\\fls0";    //  当前目录
    f_name *a=get_file_list("\\\\fls0\\*.*");    //  存储文件列表的二维数组
	int pos=0,firstn=0;    //  列表光标位置、列表下移的行数
	unsigned int key;
	char subdir_fn[32];    //  供接收子目录文件名输入的缓冲区
	FONTCHARACTER fname[64];
	int handle = 0;
	
	DefineStatusAreaFlags(3, 0x01 | 0x02 | 0x100, 0, 0);
	
	beg:
	if (a) qsort(a, getn(a), sizeof(char *), cmp);
	
	font16 = open_font("\\\\fls0\\24PX.hzk");
	select_font(font16);
	
	draw_browser(workdir,firstn,pos,a);    //  绘制浏览器界面
	
	close_font(font16);
	
	//  显示当前工作目录于状态栏
	if (strcmp(workdir, "\\\\fls0") == 0)
		DefineStatusMessage("", 0, 0, 0);
	else
	{
		memset(ncat, 0, sizeof(ncat));
		GetDisplayDirName(workdir, ncat);
		DefineStatusMessage(ncat, 0, 0, 0);
	}
	
	while (1)
	{
	    GetKey(&key);
		switch (key)
		{
		    case KEY_CTRL_UP:    //  光标上移
			    if (a)
				{
				    aa(&pos,&firstn,getn(a));
					goto beg;
				}
				break;
				
			case KEY_CTRL_DOWN:    //  光标下移
			    if (a)
				{
				    bb(&pos,&firstn,getn(a));
					goto beg;
				}
				break;
			
			case KEY_CTRL_F6:    //  显示关于信息
			    Disp_About();
				goto beg;
				break;
			
			case KEY_CTRL_F1:    //  打开光标位置的文件
			case KEY_CTRL_EXE:
			    if (a)    //  如果文件列表不为空
			    {
			        if (strchr(a[pos+firstn].name,'['))    //  如果打开的是文件夹
				    {
				        memset(ncat,0,sizeof(ncat));
					    //strcat(ncat,"\\\\fls0\\");
						strcat(ncat, workdir); strcat(ncat, "\\");
				        strcat(ncat, ++a[pos+firstn].name);
					    memset(workdir, 0, sizeof(workdir));
					    strcpy(workdir, ncat);
					    strcat(ncat, "\\*.*");    //  解析出文件夹名称
					    a=get_file_list(ncat);    //  浏览该文件夹
						pos=0; firstn=0;    //  列表初始化
					    goto beg;
				    }
				    else    //  如果打开的是文本文件
				    {	
						memset(ncat,0,sizeof(ncat));
				        strcpy(ncat,workdir);
						strcat(ncat,"\\");
				        strcat(ncat,a[pos+firstn].name);    //  解析出文件名称
						
						iRead_main(ncat);    //  启动阅读器
						goto beg;
				    }
				}
				break;
				
			case KEY_CTRL_F2:	//  根据输入的文件名打开文件
				memset(subdir_fn, 0, sizeof(subdir_fn));
				if (Subdir_Open(subdir_fn))
				{
					memset(ncat, 0, sizeof(ncat));
				    strcpy(ncat, workdir);
					strcat(ncat, "\\");
				    strcat(ncat, subdir_fn);    //  连接上输入的文件名字
					strcat(ncat, ".txt");
						
					char_to_font(ncat, fname);
					handle = Bfile_OpenFile_OS(fname,0);
					if (handle <= 0)    //  如果文件未找到
					{
						Disp_FileNotFound();
						MsgBoxPop();
						goto beg; break;
					}
						
					MsgBoxPop();
					Bfile_CloseFile_OS(handle);
					
					//  重新绘制浏览器界面
					font16 = open_font("\\\\fls0\\24PX.hzk");
					select_font(font16);
	
					draw_browser(workdir, firstn, pos, a);
					close_font(font16);
					
					//  启动阅读器
					iRead_main(ncat);
				}
				
				goto beg; break;
			
			case KEY_CTRL_EXIT:    //  从文件夹返回根目录
			    if (strcmp(workdir,"\\\\fls0")!=0)    //  如果当前在文件夹内
			    {
			        memset(ncat,0,sizeof(ncat));
			        strncpy(ncat,workdir,strlen(workdir)-strlen(strrchr(workdir,'\\')));
				    memset(workdir,0,sizeof(workdir));
				    strcpy(workdir,ncat);
				    strcat(ncat,"\\*.*");    //  解析出上一级目录的名称
			        a=get_file_list(ncat);    //  浏览该文件夹
					pos=0;firstn=0;    //  初始化列表
				    goto beg;
				
				}
				break;
			
		}
	}
}
Esempio n. 9
0
File: main.c Progetto: ExAcler/Prizm
void iRead_main(const char* filename)
{
    /*
	    阅读界面主函数
		参数说明:
		    filename: 打开的文件名 (从文件浏览器得到)
	*/

    int key,handle;
	char* buf=(char*)malloc(461);
	FONTCHARACTER fname[64];
	
	char tip[64], tmp[64];
	
	page=0;cached=0;
	
	memset(bytes,0,sizeof(bytes));
	memset(bookmark,0,sizeof(bookmark));bookmark[3]=0;
	
	Read_Config(filename,&cached);    //  读取书签及分页配置
	
	//  如果分的页数不满 500 的整数倍,补分页满
	if (cached==0) divide_page(filename,500-cached,1);
	else
	    if (cached%500!=0) divide_page(filename,500-cached%500,1);   // 补至 500 的整数倍
	totbytes=0;
	
	/*  设置状态栏显示文字
		0x0001:显示电量
		0x0100:显示文字
	*/
	DefineStatusAreaFlags(3, 0x01 | 0x02 | 0x100, 0, 0);
	
	beg:
	font16=open_font("\\\\fls0\\24PX.hzk");
	select_font(font16);
	
	Bdisp_AllClr_VRAM();
    draw_pic(0,192,124,22,0,Menu_Read);
	draw_pic(126,192,61,22,0,Menu_Sub_Jump);
	
	//  若翻下一页时超出已缓存页面范围
	if (cached<=page)
	{
	    //  如果分的页数不满 500 的整数倍,补分页满
	    if (!divide_page(filename,1,0)) page=cached-1;
	    else if (cached%500!=0) divide_page(filename,500-cached%500,0);
		
		close_font(font16);
		goto beg;
	}
	totbytes=bytes[page];    //  修正读取字节指针位置
	
	char_to_font(filename,fname);
	handle=Bfile_OpenFile_OS(fname,0);    //  打开文件
	
	Bfile_ReadFile_OS(handle,buf,400,totbytes);
	Bfile_CloseFile_OS(handle);
	
	print_chs_page(0,24,totbytes,(unsigned char*)buf);    //  绘制一页
    close_font(font16);
	
	//  准备显示浏览进度
	char fn_ptr[64];
	memset(fn_ptr, 0, sizeof(fn_ptr));
	GetDisplayFileName(filename, fn_ptr);
	
	memset(tip, 0, sizeof(tip));
	memset(tmp, 0, sizeof(tmp));
	strcat(tip, fn_ptr); strcat(tip, " ");
	itoa(page + 1, tmp, 10); strcat(tip, tmp);
    strcat(tip, "/"); memset(tmp, 0, sizeof(tmp));
	itoa(cached, tmp, 10);strcat(tip, tmp);
	
	//  状态栏显示文件名及进度
	DefineStatusMessage(tip, 0, 0, 0);
	
	while (1)
	{
	    GetKey(&key);
	    switch (key)
		{
		    case KEY_CTRL_UP:    //  跳到上一页
			    if (page>0)
				{
			        --page;
				    goto beg;
				}
				break;
				
		    case KEY_CTRL_DOWN:    //  跳到下一页
			    ++page;
			    goto beg;
				break;
				
			case KEY_CTRL_EXIT:    //  离开,返回文件浏览器
			    Save_Config(filename,cached+1);
				DefineStatusAreaFlags(3, 0x01 | 0x02 | 0x100, 0, 0);
			    return;break;
				
			case KEY_CTRL_F2:    //  打开存储书签对话框
			    Save_Bookmark(filename,page,cached+1);
				goto beg;break;
				
			case KEY_CTRL_F1:    //  打开读取书签对话框
			    Read_Bookmark(filename,&page,&cached);
				goto beg;break;
				
			case KEY_CTRL_F3:    //  打开跳页对话框
			    Page_Jump(filename);
				goto beg;break;
		}
 	}
}
Esempio n. 10
0
File: main.c Progetto: ExAcler/Prizm
int divide_page(const char* filename,const int pages,int save)
{
    /*
	    分页函数
        参数说明:
	        filename: 当前打开文件的文件名
            pages: 需要分的页数
            save: 是否需要跳回第一页 (初始化时使用)
		返回值:
		    0: 已读到文件末尾
			1: 未读到文件末尾
    */

    int cx,cy;
    int i=0,j;
    const int pp=16;
	int is_chs=0;  // 中文字符标识
	int tmp=cached,total=0;
	
	int decades_passed = 1;
	
	int handle;
	char* buf=(char*)malloc(460);
	FONTCHARACTER fname[64];
	
    char_to_font(filename,fname);
	handle=Bfile_OpenFile_OS(fname,0);
	tmp=cached;
	totbytes=bytes[cached];  // 保险修正
	
	// 如果请求的页数超过 9999 页,修正为 9999 页
	if ((total=tmp+pages)>9999) total=9999;
	// 在 9999 页时尝试往后翻一页,跳出
	if (cached+1>9999) {Bfile_CloseFile_OS(handle);return 0;};
	
	// 在屏幕上显示分页的进度
	ProgressBar(0, total - tmp);
	
	for (j=tmp;j<total;++j)    //  从当前已缓存页面分到请求的页面,使用模拟填充显示区域方法
	{
	    // 尝试读取一段文字以备分页
	    memset(buf,0,461);
	    Bfile_ReadFile_OS(handle,buf,400,totbytes);
		// 如果读到文件末尾则跳出
		if (!buf[0])
		{
			ProgressBar(total - tmp, total - tmp);
			Bfile_CloseFile_OS(handle);
			MsgBoxPop();
			return 0;
		}
		
		// 填充位置设置为初始状态
        cx=0;
		cy=24;
		
        for (i=0;;)
        {
            is_chs=buf[i] & 0x80;  // 判断高位字节,确定是否为中文
            if ((cx+pp)>368)  // 填充超过屏幕右边缘
                goto cn;
            if (is_chs) i+=2;  // 中文,跳2字节
            else
            {
		        if (buf[i] == '\r' || buf[i] == '\n')  // 若读到回车符直接进入下一行
			    {
			        i++;
					if (buf[i] == '\r' || buf[i] == '\n')  // 若读到回车符直接进入下一行
						i++;
				    goto cn;
			    }
			    i++;
            }
        
		    // 将字符填充入当前行,增加字符偏移
		    if (is_chs)
                cx+=25;
		    else
		        cx+=18;
        
		    // 填充超过屏幕右边缘
            if (cx>368)
            {
            cn:
                cx=0;
                cy+=24;  // 增加纵向字符偏移,进入下一行
			    if (cy>190)  // 填充超过屏幕下边缘,跳出
			        break;
            }
        }
	    bytes[j+1]=i+totbytes;  // 将最后一个字符在文件中的位置存入下一页的缓存,以备读取
		totbytes+=i;  // 读取字节指针增加
	    ++cached;  // 已缓存页面增加,表示分页成功
		
		// 每分完1/10的总体,增加进度显示
		if (j - tmp == (total - tmp) / 10 * decades_passed)
		{
			ProgressBar(j - tmp, total - tmp);
			decades_passed++;
		}
	}
	if (save) page=0;    // 跳回第一页  
	
	ProgressBar(total - tmp, total - tmp);
	Bfile_CloseFile_OS(handle);
	MsgBoxPop();
	return 1;
}
Esempio n. 11
0
void input_eval_loop(int isRecording) {
  char** recHistory = NULL; int curRecHistEntry = 0;
  if(isRecording) recHistory = (char**)alloca(200); // space for 200 pointers to history entries
  while (1) {
    DefineStatusMessage((char*)"", 1, 0, 0);
    strcpy(expr, (char*)"");
    printf("\x1e");
    dConsoleRedraw();
    int res = gets(expr,INPUTBUFLEN);
    if(res == 2) {
      dConsolePut("\n");
      select_script_and_run();
      continue;
    }
    if(res == 4) {
      dConsolePut("\n");
      select_strip_script();
      continue;
    }
    if(res == 3) {
      dConsolePut("\n");
      char buf[100] = "";
      sprintf(buf, "prizmUIkeyHandler(%d,%d)", custom_key_to_handle, custom_key_to_handle_modifier);
      strcpy(expr, (char*)buf);
      execution_in_progress = 1;
      run(buf);
      execution_in_progress = 0;
      check_do_graph();
      if(run_startup_script_again) { run_startup_script_again = 0; run_startup_script(); }
      continue;
    }
    puts(expr);
    update_cmd_history(expr);
    dConsoleRedraw();
    if(strcmp(expr, "testmode") == 0) {
      TestMode(1);
    } else if(strcmp(expr, "meminfo") == 0) {
      print_mem_info();
    } else if(strcmp(expr, "memgc") == 0) {
      gc();
    } else if(strcmp(expr, "record") == 0) {
      if(!isRecording) script_recorder();
      else {
        // create and save a script. this must be done here, because we used alloca
        // the "clean" way would be using malloc&free, but on the Prizm the heap is already being heavily used by the Eigenmath core.
        if(curRecHistEntry == 0) {
          printf("Nothing to record.\n");
          return;
        }
        printf("Recording stopped.\n");
        printf("Type a name for the script, or\n");
        printf("leave empty to discard.\n:");
        char inputname[MAX_FILENAME_SIZE+1] = "";
        gets(inputname,MAX_FILENAME_SIZE-50);
        puts(inputname);
        if(!strlen(inputname)) {
          // user aborted
          printf("Recording discarded.\n");
          return;
        }
        if (aborttimer > 0) {
          Timer_Stop(aborttimer);
          Timer_Deinstall(aborttimer);
        }
        char filename[MAX_FILENAME_SIZE+1] = "";
        sprintf(filename, "\\\\fls0\\%s.txt", inputname);
        unsigned short pFile[MAX_FILENAME_SIZE+1];
        Bfile_StrToName_ncpy(pFile, (unsigned char*)filename, strlen(filename)+1);
        // calculate size
        int size = 0;
        int maxHistory = curRecHistEntry - 1; //because we ++'ed at the end of last addition
        for(int i=0; i <= maxHistory; i++) {
          size = size + strlen(recHistory[i]) + 1; // 1 byte for \n. we will use unix line termination
        }
        int BCEres = Bfile_CreateEntry_OS(pFile, CREATEMODE_FILE, &size);
        if(BCEres >= 0) // Did it create?
        {
          BCEres = Bfile_OpenFile_OS(pFile, READWRITE, 0); // Get handle
          for(int i=0; i <= maxHistory; i++) {
            char* buf = (char*)alloca(strlen(recHistory[i])+5);
            strcpy(buf, recHistory[i]);
            strcat(buf, (char*)"\n");
            Bfile_WriteFile_OS(BCEres, buf, strlen(recHistory[i])+1);
          }
          Bfile_CloseFile_OS(BCEres);
          printf("Script created.\n");
        } else {
          printf("An error occurred when creating the script for recording.\n");
        }
        aborttimer = Timer_Install(0, check_execution_abort, 100);
        if (aborttimer > 0) Timer_Start(aborttimer);
        return;
      }
    } else {
      execution_in_progress = 1;
      has_drawn_graph = 0;
      run(expr);
      // run_startup_script cannot run from inside eval_clear because then it would be a run() inside a run()
      if(run_startup_script_again) { run_startup_script_again = 0; run_startup_script(); }
      execution_in_progress = 0;
      
      // if recording, add input to record
      if(isRecording && curRecHistEntry <= 200) {
        recHistory[curRecHistEntry] = (char*)alloca(strlen(expr)+2); // 2 bytes for security
        strcpy(recHistory[curRecHistEntry], expr);
        curRecHistEntry++;
      }
      check_do_graph();
    }
  }
}
Esempio n. 12
0
void select_strip_script() {
  if(!is_running_in_strip()) {
    printf("This function is only available\n");
    printf("when running as an eActivity\n");
    printf("strip.\n");
    return;
  }
  
  textArea text;

  textElement elem[10];
  text.elements = elem;
  
  elem[0].text = (char*)"This function lets you run a script when this eActivity strip is opened.";
  elem[1].newLine = 1;
  elem[1].text = (char*)"When sharing the eActivity file, it will not be necessary to share any other files - the script is included in the eActivity.";
  elem[2].newLine = 1;
  elem[2].text = (char*)"You will be informed if the script is too big to fit inside the eActivity file.";
  elem[3].newLine = 1;
  elem[3].text = (char*)"Press EXIT now to continue and select a script.";
  text.numelements = 4;
  doTextArea(&text);
  
  char filename[MAX_FILENAME_SIZE+1] = "";
  if(fileBrowser(filename, (unsigned char*)"*.txt", "Scripts")) {
    // get the size of the selected script on SMEM.
    // get free size on the "MCS" of the strip we're running on and see if the script fits
    unsigned short pFile[MAX_FILENAME_SIZE+1];
    Bfile_StrToName_ncpy(pFile, (unsigned char*)filename, strlen(filename)+1); 
    int hFile = Bfile_OpenFile_OS(pFile, READWRITE, 0); // Get handle
    if(hFile >= 0) // Check if it opened
    { //opened
      unsigned int filesize = Bfile_GetFileSize_OS(hFile);  
      //get free size of MCS
      int MCSmaxspace; int MCScurrentload; int MCSfreespace;  
      MCS_GetState( &MCSmaxspace, &MCScurrentload, &MCSfreespace );
      if((int)filesize < MCSfreespace - 50) { // 50 bytes for any headers and the like
        // fits, copy selected script to MCS
        unsigned char* scontents = (unsigned char*)alloca(filesize);
        memset(scontents, filesize, 0);
        int rsize = Bfile_ReadFile_OS(hFile, scontents, filesize, 0);
        scontents[rsize]='\0';
        // script is now in buffer scontents
        // write it to the "MCS"
        int createResult = MCS_CreateDirectory( DIRNAME );
        if(createResult != 0) // Check directory existence
        { // directory already exists, so delete the exiting file that may be there
          MCSDelVar2(DIRNAME, SCRIPTFILE);
        }
        MCSPutVar2(DIRNAME, SCRIPTFILE, rsize, scontents);
        printf("Script set successfully.\n");
      } else {
        printf("The script is too big to be\n");
        printf("included in the eActivity.\n");
      }
      Bfile_CloseFile_OS(hFile);
      return; // don't get to the error message
    }
  }
  printf("There was a problem setting the script for this strip.\n");
}
Esempio n. 13
0
void textfileEditor(char* filename, char* basefolder) {
  int newfile = (filename == NULL);
  char sText[TEXT_BUFFER_SIZE] = "";
  if(!newfile) {
    newfile = 0;
    int openerror = 0;
    int hFile = fileOpen(filename); // Get handle
    if(hFile >= 0) // Check if it opened
    { //opened
      unsigned int filesize = Bfile_GetFileSize_OS(hFile);
      if(!filesize || filesize > TEXT_BUFFER_SIZE) {
        openerror = 1;
      } else {
        Bfile_ReadFile_OS(hFile, sText, TEXT_BUFFER_SIZE, 0);
      }
      Bfile_CloseFile_OS(hFile);
    } else {
      openerror = 1;
    }
    if(openerror) {
      //Error opening file, abort
      AUX_DisplayErrorMessage(0x2B); // Data ERROR
      return;
    }
  }
  textEdit input;
  //input.forcetext=1;
  input.charlimit=TEXT_BUFFER_SIZE;
  input.buffer = (char*)sText;

  // calculate checksum so we can check for changes
  unsigned char origHash[20] = "";
  sha1((unsigned char*)sText, strlen(sText), origHash);
  while(1) {
    input.key=0;
    int res = doTextEdit(&input);
    int exit = 0;
    switch(res) {
      case TEXTEDIT_RETURN_EXIT:
      {
        exit = 1;
        unsigned char newHash[20] = "";
        sha1((unsigned char*)sText, strlen(sText), newHash);
        if(!memcmp(origHash, newHash, 20)) return;
        else {
          mMsgBoxPush(4);
          mPrintXY(3, 2, "Save this file?", TEXT_MODE_TRANSPARENT_BACKGROUND,
                   TEXT_COLOR_BLACK);
          if(closeMsgBox(1, 4)) {
            // fall through
          } else {
            return;
          }
        }
      }
      case TEXTEDIT_RETURN_CONFIRM:
      {
        char newfilename[MAX_FILENAME_SIZE];
        unsigned short newfilenameshort[0x10A];
        if(newfile) {
          int backToEditor = 0;
          SetBackGround(13);
          drawScreenTitle("Text Editor", "Save file as:");
          drawFkeyLabels(0x036F); // <
          textInput ninput;
          ninput.forcetext=1;
          ninput.charlimit=MAX_NAME_SIZE;
          char nfilename[MAX_NAME_SIZE];
          nfilename[0] = 0;
          ninput.buffer = (char*)nfilename;
          while(1) {
            ninput.key = 0;
            int nres = doTextInput(&ninput);
            if (nres==INPUT_RETURN_EXIT || (nres==INPUT_RETURN_KEYCODE && ninput.key==KEY_CTRL_F1)) {
              // user aborted
              backToEditor = 1;
              break;
            } else if (nres==INPUT_RETURN_CONFIRM) {
              if(stringEndsInG3A(nfilename)) {
                mMsgBoxPush(4);
                multiPrintXY(3, 2, "g3a files can't\nbe created by\nan add-in.",
                             TEXT_MODE_TRANSPARENT_BACKGROUND, TEXT_COLOR_BLACK);
                closeMsgBox();
              } else {
                // create and save file
                strcpy(newfilename, basefolder);
                strcat(newfilename, nfilename);
                Bfile_StrToName_ncpy(newfilenameshort, newfilename, 0x10A);
                break;
              }
            }
          }
          if(backToEditor) continue;
        } else {
          // delete, then create and save file
          Bfile_StrToName_ncpy(newfilenameshort, filename, 0x10A);
          Bfile_DeleteEntry(newfilenameshort);
        }
        size_t size = strlen(sText);
        if(Bfile_CreateEntry_OS(newfilenameshort, CREATEMODE_FILE, &size) < 0) { //create the file
          // it appears file exists, overwrite?
          if(overwriteFilePrompt(newfilename)) {
            Bfile_DeleteEntry(newfilenameshort);
            Bfile_CreateEntry_OS(newfilenameshort, CREATEMODE_FILE, &size);
          }
          else continue; // abort file save so user can discard the file, or type another filename.
        }
        
        int h = Bfile_OpenFile_OS(newfilenameshort, READWRITE, 0);
        if(h >= 0) { // Still failing?
          //Write file contents
          Bfile_WriteFile_OS(h, sText, size);
          Bfile_CloseFile_OS(h);
          // clear unsaved changes "flag":
          sha1((unsigned char*)sText, strlen(sText), origHash);
        }
        if(exit) return;
      }
      break;
    }
  }
}
Esempio n. 14
0
void passwordGenerator() {
  Menu menu;
  menu.type = MENUTYPE_FKEYS;
  menu.title = (char*)"Password Generator";
  menu.height = 7;
  MenuItem items[6];
  int length = 10;
  int seed = RTC_GetTicks() * (GetMainBatteryVoltage(1) % 100);
  char lstr[10];
  items[1].text = (char*)"Include symbols";
  items[1].type = MENUITEM_CHECKBOX;
  items[2].text = (char*)"Include numbers";
  items[2].type = MENUITEM_CHECKBOX;
  items[2].value = MENUITEM_VALUE_CHECKED;
  items[3].text = (char*)"Include uppercase";
  items[3].type = MENUITEM_CHECKBOX;
  items[3].value = MENUITEM_VALUE_CHECKED;
  items[4].text = (char*)"Include confusable";
  items[4].type = MENUITEM_CHECKBOX;
  items[4].value = MENUITEM_VALUE_CHECKED;
  items[5].text = (char*)"Memorable vowel mix";
  items[5].type = MENUITEM_CHECKBOX;
  menu.numitems = 6;
  menu.items = items;
  while(1) {
    drawFkeyLabels(0x03B3, 0, 0, 0, 0, 0x0184); // FILE, EXE (white)
    itoa(length, (unsigned char*)lstr);
    char t[20];
    strcpy(t, "Length: ");
    strcat(t, lstr);
    items[0].text = t;
    switch(doMenu(&menu)) {
      case MENU_RETURN_EXIT:
        return;
      case MENU_RETURN_SELECTION:
        if(menu.selection > 1) items[menu.selection-1].value = !items[menu.selection-1].value;
        else {
          Selector sel;
          sel.min = 6;
          sel.value = length;
          sel.max = 30;
          sel.cycle = 1;
          sel.title = (char*)"Password Generator";
          sel.subtitle = (char*)"Length";
          if(doSelector(&sel) == SELECTOR_RETURN_SELECTION) {
            length = sel.value;
          }
        }
        break;
      case KEY_CTRL_F1:
      {
        Selector sel;
        sel.min = 1;
        sel.value = 10;
        sel.max = 1000;
        sel.cycle = 1;
        sel.title = (char*)"Generate to file";
        sel.subtitle = (char*)"Number of passwords";
        if(doSelector(&sel) != SELECTOR_RETURN_SELECTION) break;

        SetBackGround(10);
        drawScreenTitle("Generate to file", "Filename:");
        char newname[MAX_NAME_SIZE];
        newname[0] = 0;
        textInput input;
        input.forcetext=1;
        input.symbols = 0;
        input.charlimit=MAX_NAME_SIZE;
        input.buffer = (char*)newname;
        int inscreen = 1;
        while(inscreen) {
          input.key=0;
          int res = doTextInput(&input);
          if (res==INPUT_RETURN_EXIT) break; // user aborted
          else if (res==INPUT_RETURN_CONFIRM) {
            inscreen = 0;
          }
        }
        if(inscreen) break;
        char newfilename[MAX_FILENAME_SIZE];
        strcpy(newfilename, SMEM_PREFIX);
        strcat(newfilename, newname);
        strcat(newfilename, ".txt");
        unsigned short pFile[0x10A];
        Bfile_StrToName_ncpy(pFile, newfilename, 0x10A);
        unsigned int size = 1;
        int ntry = 0;
        while(ntry < 2) {
          ntry++;
          int BCEres = Bfile_CreateEntry_OS(pFile, CREATEMODE_FILE, &size);
          if(BCEres >= 0) {
            int hFile = Bfile_OpenFile_OS(pFile, READWRITE, 0); // Get handle
            if(hFile >= 0) {
              char password[35];
              char line[37];
              for(int i = 0; i < sel.value; i++) {
                generateRandomString(password, length, items[1].value, items[2].value,
                                     items[3].value, items[4].value, items[5].value, &seed);
                sprintf(line, "%s\r\n", password);
                Bfile_WriteFile_OS(hFile, line, length+2);
              }
              Bfile_CloseFile_OS(hFile);
            } else AUX_DisplayErrorMessage(0x2B);
            break;
          } else if(ntry < 2) {
            // File creation probably failed due to the presence of a file with the same name
            if(overwriteFilePrompt(newfilename))
              Bfile_DeleteEntry(pFile);
            else
              break;
          } else AUX_DisplayErrorMessage(0x2B);
        }
        break;
      }
      case KEY_CTRL_F6:
        int inscreen = 1;
        while(inscreen) {
          Bdisp_AllClr_VRAM();
          drawScreenTitle("Password Generator", "Generated passwords:");
          textArea text;
          text.type = TEXTAREATYPE_INSTANT_RETURN;
          text.scrollbar = 0;
          text.y = 48+3;
          text.lineHeight = 20;
          textElement e[5];
          char passwords[5][35];
          for(int i = 0; i < 5; i++) {
            generateRandomString(passwords[i], length, items[1].value, items[2].value,
                                 items[3].value, items[4].value, items[5].value, &seed);
            e[i].text = passwords[i];
            if(i) e[i].newLine = 1;
          }
          text.elements = e;
          text.numelements = 5;
          doTextArea(&text);
          drawFkeyLabels(0x036F, 0, 0, 0, 0, 0x02B9); // <, REPEAT (white)
          while(1) {
            int key;
            mGetKey(&key);
            if(key == KEY_CTRL_F6) break;
            if(key == KEY_CTRL_F1 || key == KEY_CTRL_EXIT) {
              inscreen = 0;
              break;
            }
          }
        }
        break;
    }
  }
}
Esempio n. 15
0
int CreateFileMapping(const unsigned short *pFileName,FileMapping *pMap){
	int iResult = 0;
	char cBuffer[FLASH_PAGE_SIZE];
	int hFile = Bfile_OpenFile_OS(pFileName,0,0);
	int iLength;
	char *pFlashFS = (char *)FLASH_START;

	pMap->miItemCount = 0;
	pMap->miTotalLength = 0;
	iLength = Bfile_ReadFile_OS(hFile,cBuffer,FLASH_PAGE_SIZE,-1);
	while(iLength > 0)
	{
		//do not optimize (= do not move these 2 variables before loop)!
		// fx-cg allocates pages for file in <random> order so page from the end of the file 
		//can have lower index than page from the beginning
		const char *pTgt = pFlashFS;
		int iPageIndx = 0;

		for(;iPageIndx < FLASH_PAGE_COUNT;iPageIndx++)
		{
			if(!Xmemcmp(pTgt,cBuffer,iLength))
			{
				break;
			}
			pTgt += FLASH_PAGE_SIZE;
		}
		if(iPageIndx == FLASH_PAGE_COUNT)
		{
			//page not found !
			iResult = -2;
			goto lbExit;
		}
		pMap->miItemCount ++;
		if(pMap->miItemCount >= MAX_FRAGMENTS)
		{
			//file too fragmented !
			iResult = -3;
			goto lbExit;
		}
		pMap->mTable[pMap->miItemCount-1].msOffset = (short)iPageIndx;
		pMap->mTable[pMap->miItemCount-1].msCount = 0;
		//assume fragment has more pages
		for(;;)
		{
			pMap->mTable[pMap->miItemCount-1].msCount++;
			pMap->miTotalLength += iLength;
			iPageIndx++;
			pTgt += FLASH_PAGE_SIZE;

			if(iLength < FLASH_PAGE_SIZE)
			{
				//this was the last page
				iResult = pMap->miTotalLength;
				goto lbExit;
			}
			iLength = Bfile_ReadFile_OS(hFile,cBuffer,FLASH_PAGE_SIZE,-1);
			if(iLength <= 0)
			{
				break;
			}
			if(Xmemcmp(pTgt,cBuffer,iLength))
			{
				break;
			}
		}
	}
	if(iLength < 0)
	{
		iResult = -1;
	}
	else
	{
		if(pMap->miTotalLength >50000)
		{
			pMap->miTotalLength = 50000;//hack
		}

		iResult = pMap->miTotalLength;
	}

lbExit:
	Bfile_CloseFile_OS(hFile);
	return iResult;

}