2010年8月13日 星期五

[Javascript] 處理 binary 的編碼問題

之前 把玩 Booktorious 時,碰到編碼的問題。苦思良久,今天發現,原來 Booktorious 的片段程式碼早就解決了!只是他只用在 XHTML 檔案而已。


整個流成是將一個 EPUB/ZIP 檔案,以 binary 型態讀進 Javascript 變數中,接著使用 js-unzip 和其相關套件,將變數所儲存的資料進行解壓縮,該 EPUB 檔案主要是一些 XHTML 或 XML 組成,緊接著分批處理那些 XHTML 跟 XML 檔案,在 Booktorious 已經很完善地解決完 XHTML 部份,然而,有些文件是 XML 部份則有編碼的問題。


EPUB TEST


過去我一直認為,因為 XML 檔案描述不夠完整,導致瀏覽器無法顯示正確的編碼,如上圖左邊書目,此資料來源是一個 XML 檔案。認為資料一開始以 binary 的方式儲存在 Javascript 變數中,因為過程是從 zip 檔案解壓縮產生並未透過瀏覽器而無法處理編碼(把該 XML 檔解壓縮出來,直接用瀏覽器看則會顯示正確編碼),加上自己對 Javascript 不熟深深,覺得這大概是個瓶頸了!


在仔細確認一次 Booktorious 處理 XHTML 的部份,驚覺過程中用到了一個關鍵的步驟:


var data = decodeURIComponent(escape( raw_data ) );


其中 raw_data 就是從 EPUB 檔案透過 js-unzip 解壓縮出來的一個 XML 檔案內容,若編碼非英文,單純用 console.log( raw_data ); 則會看到亂碼。如今透過上述兩個函式的處理,則 data 就是按照內文中的編碼呈現。


最後的成果,就是正確書目囉


EPUB


2010年8月11日 星期三

[Javascript] 把玩 Booktorious

EPUB


Booktorious 是一套純 Javascript 的 EPUB reader,單純接收一個 *.epub 檔案,接著用 Javascript 進行 unzip ,接著再依照 EPUB 格式進行 parsing ,最終則把 EPUB 的內容用多個 iframe 依序成列出來。這是一套 open source 的 framework,這陣子花了一點時間把玩,此預設一次把 EPUB 全部 parsing 完,而我想更改成挑選章節的解壓縮方式。


粗略筆記原先的過程:



  1. 透過 HTML5 的 FileReader 物件,將 user 端的檔案讀進 Javascript 裡處理

  2. 使用 JSEPUB 物件進行 EPUB 檔案的處理

  3. JSEPUB 物件接著會將整個 EPUB 進行初步 unzip 的處理,如果壓縮檔跟作者所撰寫的 ZIP 或 EPUB 格式不符,則會停下來

  4. 分析 EPUB 的 META-INF/container.xml 檔案,從中得知 content.opf 位置

  5. 分析 content.opf 資訊,得知 EPUB 內所有的檔案清單與格式

  6. 依照檔案格式,如 text/css 、application/xhtml+xml 進行處理,像 XHTML 部份,處理裡頭的連結位置,甚至用到的圖片資訊會從連結改用成內嵌的方式呈現 ( src="data,image/jpeg,....." ),並透過 new DOMParser().parseFromString() 轉成 DOM 物件

  7. 最後將各個 XHTML 之 DOM 模式,再透過 new XMLSerializer().serializeToString() 寫到 iframe 裡頭呈現於網頁


我想嘗試的,則是第三步起,不對整個 EPUB 檔案作解壓縮,只依序對 META-INF/container.xml、content.opf、toc.ncx 以及對該 EPUB 的第一章或封面進行解壓縮處理。


嘗試的成果,碰到問題



  • content.opf 和 toc.ncx 亂碼問題(如上圖左邊的書目)

  • toc.ncx 其中 href 使用 test.html#123 這種用 '#tag' 方式的連結問題


前者部份,由於是 xml 格式,雖然有標明 UTF-8 編碼等等,但我單純從 Javascript 讀 EPUB、解壓縮、拿到該 xml 資料、進行 dom parsing 等等動作,都是在 Javascript 以 binary 處理,處理完仍是亂碼。若這些檔案單純用 browser 去瀏覽,則可以顯示正確的編碼。不曉得是不是獨缺給 browser 碰一下的過程,因此無法顯示正確的編碼,但如果是以 xhtml 檔案,則都可以正確呈現;對於 toc.ncx 裡頭,有些章節並不是指到一檔案而已,而是某個 XHTML 檔案的某個段落,因此就要處理如何呈現到正確位置。請教米蟲大神後,得知既然是用 JS 產生 HTML ,那則可以對該物件進行 location 的操作,如 data.location = '#tag'; 的方式。只是我測試的結果,僅能對 webkit 成功,像 Firefox 的就無法正確處理。


上述中連結解法,片段程式:


var obj_div = document.getElementById( 'show' );  // <div id="show"></div>
var data = xhtml_dom_structure;                           // 一個 xhtml 檔案,已透過 DOMParser 處理
var iframe = document.createElement("iframe");    // 動態產生 iframe
var target = '#tag';                                                // 打算指到 test.xhtml#tag 位置

var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow ? iframe.contentWindow : iframe.document ? iframe.document : null;

if(doc == null)
    throw "Document not initialized";

doc.open();
doc.write( new XMLSerializer().serializeToString(data) );
doc.close();

if( target && doc.defaultView && doc.defaultView.location )
    doc.defaultView.location = target;


因此也不算是解掉,僅能在 Google Chrome 或 Safari 使用。


原先只是單純想把 EPUB 解壓縮從全部解壓縮改成部份解壓縮,以此加速呈現,經過幾番測試,速度的確可以拉到 1 秒內完成,但這是在 AMD X4 945 的主機,並搭配 Google Chrome 的成果。以一個 1MB 的檔案,預設全解花 6.5 秒左右(使用Firefox約 13 秒),改成只解開必要的以及第一章約 0.2 秒就可以完工了!但是,移到 iPad 上測試卻要花 8 秒處理!更何況是 iPhone 3G 呢(事實上iPhone 3G + iOS4並未正常執行該程式,因此無法測試所需時間)。


最後,如果 EPUB 的壓縮格式有問題,可以試著解壓縮後重新壓縮,其指令如下:


$ unzip test.epub -d test
$ cd test
$ zip -0Xq ../new.epub mimetype
$ zip -Xr9D ../new.epub *


另外,也可以確認一下 mimetype 內容是否為 "application/epub+zip"


簡單的 bash


#!/bin/sh
if [ -z $1 ]; then
        echo ''
        echo 'This is a tool to zip current work dir in to an EPUB file'
        echo ''
        echo 'Usage>' $0 'output_path.epub'
        echo ' e.g. ' $0 '/tmp/out.epub'
        return
fi

if [ ! -e 'mimetype' ]; then
        echo '[Error] No mimetype'
        return
fi

if [ ! -e 'META-INF/container.xml' ]; then
        echo '[Error] No META-INF/container.xml'
        return
fi

zip -0Xq $1 mimetype
zip -Xr9D $1 *


2010年8月2日 星期一

[Javascript] 讀取 Binary 資料存入變數中

將檔案資料讀取到 Javascript 變數中,大概可以分成兩個方向,一種是將遠端的檔案透過 URL 讀取進來,另一種則是從本地端透過使用者選取的檔案讀取進來。在此後者使用 HTML5 的 File API 進行處理。


先提一下遠端檔案, Ajax query 雖然已經很常見了,但對於要將讀取的資料以 binary 姿態儲存在變數之中,還是需要額外處理:


var raw_data = null;


var path = "test_file.zip";
var ajReq = new XMLHttpRequest();

try
{
        ajReq.open( 'GET' , path , false );
        ajReq.overrideMimeType( 'text/plain; charset=x-user-defined' );
        ajReq.send(null);

        var out = ajReq.responseText || '' ;

        var out_array = [];

        for( var i=0, len=out.length, scc=String.fromCharCode ; i<len ; ++i )

                out_array[i] = scc( out.charCodeAt(i) & 0xff );

        raw_data = out_array.join( '' );

}
catch( err )
{
        alert( 'Error:' + err );
}


而從本地端讀取使用者所選取的檔案,則使用 HTML5 - File API , FileReader


function getRawData( raw_data )
{

}

var reader = new FileReader();
reader.onload = function(e){ getRawData( e.target.result ); };
if( document.getElementById('file').files[0] )
{
        reader.readAsBinaryString( document.getElementById('file').files[0] );
}


其中在 HTML 裡,有個 <input id="file" type="file" />,而 FileReader 似乎滿好玩的,還有 readAsDataURL 可以玩玩


此例可在 Firefox 3.6 或 Google Chrome 6 等支援 HTML5 的瀏覽器中測試


2010年8月1日 星期日

[PHP] 從 5.2.x 升到 5.3.x 的問題處理 @ FreeBSD

最近查看了以前的測試機器,發現原先用的 PHP 5.2.x 系列已經被更新成 5.3.x 系列,並且連執行個 php -v 會出現 Segmentation fault,上網隨意找到一些資訊,大概是 5.3.x 系列已經包括一些常用的 lib 進來,再次請教一下學弟,發現他已處理過這方面的問題,僅需在 php5-extension 去移除那些套件,另外則是 extensions.ini 須去除或註解一些套件,如此一來便可以處理完畢。雖然我修到 php -v 不會出現問題,但還是有些 lib 不能正常運行。甚至從編譯 php5-extension 仍會出錯,主要卡在 PCRE 的部分。


參考資料


php5-extensions-1.4 Upgrade Failure, php5-filter-5.3.2, php5-imap-5.3.2 and pcre issues: Stop in /usr/ports/security/php5-filter


最後解法


查看目前安裝的 PHP 相關套件


# pkg_info | grep php


使用 pkg_delete 把他們都移除掉

# pkg_info | grep php5 | awk '{system("pkg_delete " $1)}'
# pkgdb -Fu


移除備份舊 php5 資料


# mv /usr/local/etc/php /path/backup/php5/etc
# mv /usr/local/lib/php /path/backup/php5/lib
# mv /usr/local/include/php /path/backup/php5/include


編寫 /etc/make.conf


# for PHP 5.3.x
WITH_BUNDLED_PCRE="YES"


重新編譯 php5


# cd /usr/ports/lang/php5 && make deinstall clean && make rmconfig && make install


重新編譯 php5-extension


順便加上常用的套件
+CURL        CURL support
+GD          GD library support
+IMAP        IMAP support
+MBSTRING    multibyte string support
+MCRYPT      Encryption support
+OPENSSL     OpenSSL support
+PCNTL       pcntl support (CLI only)
+PSPELL      pspell support
+SOCKETS     sockets support


# cd /usr/ports/lang/php5-extensions && make deinstall clean && make rmconfig && make config && make install


2010年7月27日 星期二

iOS 開發教學 - 使用 UIToolbar + Image Button

之前學習時很偷懶,一直覺得有了 Navigation controller 和 Tabbar controller 後,總覺得畫面已經沒甚麼好擺的,所以遲遲沒有試試 UIToolbar ,這次就順手筆記一下囉。

參考資料:


程式碼:

@interface UIImage (Extras)

- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize;

@end

@implementation UIImage (Extras)

- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{

   UIImage *sourceImage = self;
   UIImage *newImage = nil;      
   CGSize imageSize = sourceImage.size;
   CGFloat width = imageSize.width;
   CGFloat height = imageSize.height;
   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;
   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;
   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
 
   if (CGSizeEqualToSize(imageSize, targetSize) == NO)
   {
       CGFloat widthFactor = targetWidth / width;
       CGFloat heightFactor = targetHeight / height;
     
       if (widthFactor > heightFactor)
           scaleFactor = widthFactor; // scale to fit height
       else
           scaleFactor = heightFactor; // scale to fit width
       scaledWidth  = width * scaleFactor;
       scaledHeight = height * scaleFactor;
     
       // center the image
       if (widthFactor > heightFactor)
       {
           thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
       }
       else
           if (widthFactor < heightFactor)
           {
               thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
           }
   }     
 
   UIGraphicsBeginImageContext(targetSize); // this will crop
 
   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;
 
   [sourceImage drawInRect:thumbnailRect];
 
   newImage = UIGraphicsGetImageFromCurrentImageContext();
   if(newImage == nil)
       NSLog(@"could not scale image");
 
   //pop the context to get back to the default
   UIGraphicsEndImageContext();
   return newImage;
}
@end

- (void)aButton:(UIButton *)sender
{
   switch (sender.tag) {
       case 1:
           NSLog(@"Facebook");
           break;
       case 2:
           NSLog(@"Twitter");
           break;
       case 3:
           NSLog(@"Tumblr");
           break;
       case 4:
           NSLog(@"Plurk");
           break;
       default:
           break;
   }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  

   // Override point for customization after application launch.
   //Initialize the toolbar

   UIToolbar *toolbar = [[UIToolbar alloc] init];
   toolbar.barStyle = UIBarStyleDefault;
   toolbar.alpha = 0.8;
 
   //Set the toolbar to fit the width of the app.
   [toolbar sizeToFit];

   //Caclulate the height of the toolbar
   CGFloat toolbarHeight = [toolbar frame].size.height;

   //Get the bounds of the parent view
   CGRect rootViewBounds = [[UIScreen mainScreen] bounds];
 
   //Get the height of the parent view.
   CGFloat rootViewHeight = CGRectGetHeight(rootViewBounds);
 
   //Get the width of the parent view,
   CGFloat rootViewWidth = CGRectGetWidth(rootViewBounds);
 
   //Create a rectangle for the toolbar
   CGRect rectArea = CGRectMake(0, rootViewHeight - toolbarHeight, rootViewWidth, toolbarHeight);
 
   //Reposition and resize the receiver
   [toolbar setFrame:rectArea];

   NSMutableArray *barButtonItemList = [[NSMutableArray alloc] init];
   CGFloat thumbWidth = 42 , thumbHeight = 42;
   {
       UIImage *image = [[UIImage imageNamed:@"facebook_icon.png"] imageByScalingAndCroppingForSize:CGSizeMake(thumbWidth, thumbHeight)];
       UIButton *button = [[UIButton alloc] init];
       [button setTag:1];
       [button setImage:image forState:UIControlStateNormal];
       [button setFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
       [button addTarget:self action:@selector(aButton:) forControlEvents:UIControlEventTouchDown];
       UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
       [button release];
       [barButtonItemList addObject:barButton];
       [barButton release];
   }
   {
       UIImage *image = [[UIImage imageNamed:@"twitter_icon.png"] imageByScalingAndCroppingForSize:CGSizeMake(thumbWidth, thumbHeight)];
       UIButton *button = [[UIButton alloc] init];
       [button setTag:2];
       [button setImage:image forState:UIControlStateNormal];
       [button setFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
       [button addTarget:self action:@selector(aButton:) forControlEvents:UIControlEventTouchDown];
       UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
       [button release];
       [barButtonItemList addObject:barButton];
       [barButton release];
   }
   {
       UIImage *image = [[UIImage imageNamed:@"tumblr_icon.png"] imageByScalingAndCroppingForSize:CGSizeMake(thumbWidth, thumbHeight)];
       UIButton *button = [[UIButton alloc] init];
       [button setTag:3];
       [button setImage:image forState:UIControlStateNormal];
       [button setFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
       [button addTarget:self action:@selector(aButton:) forControlEvents:UIControlEventTouchDown];
       UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
       [button release];
       [barButtonItemList addObject:barButton];
       [barButton release];
   }
   {
       UIImage *image = [[UIImage imageNamed:@"plurk_icon.png"] imageByScalingAndCroppingForSize:CGSizeMake(thumbWidth, thumbHeight)];
       UIButton *button = [[UIButton alloc] init];
       [button setTag:4];
       [button setImage:image forState:UIControlStateNormal];
       [button setFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
       [button addTarget:self action:@selector(aButton:) forControlEvents:UIControlEventTouchDown];
       UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
       [button release];
       [barButtonItemList addObject:barButton];
       [barButton release];
   }
   [toolbar setItems:barButtonItemList];
 
   [window addSubview:toolbar];
 
   [window makeKeyAndVisible];
 
   return YES;
}