An Ordeal of OLE

来源:互联网 发布:去黑头方法 知乎 编辑:程序博客网 时间:2024/05/23 07:24

OLE(Object Linking and Embedding) is a critical technology by Microsoft to carry out its enterprise applications, based on COM it's also a quite old one. Despite of its importance, it doesn't seem to be so necessary to me as .NET is far more than enough. However in a recent task I have to touch on it.

The task is mainly about enabling the CAD exporting library to export embedded images in addition to linked images which is supported well by both AutoCAD and the Teigha library underlying our library. After a bit of search online it was discovered that image embedding in a similar manner to image linking were not supported or suggested. There are a few solutions/workarounds including

- using OLE that embodies a paint brush application that includes the image, which is a supported feature by AutoCAD for exchanging embedded images.

- leveraging AutoCAD Raster Design (ARD) that has introduced an IEMBED command to allow images to be embeddes as they can be linked; however ARD is not part of a normal version of AutoCAD and unlikely can be easily supported by the Teigha library that we are using (however the official AutoCAD secondary development may do)

- An uncofirmed solution proposed by a discussion thread that creates an AutoCAD entity that includes the image data and is able to externalise it to a temporary file to be referenced by a normal linked image. (needs a bit investigation into how to create an object like that)

Due to the limit of time and resources available, the first option was chosen for the time being, although the third may be proven the best as OLE is neither stable nor performant when being rendered in the AutoCAD. The development of this task involved a lot of investigation and experimentation and turned out to be purely based on a copy of online queries below,

http://www.dimcax.com/hust/showpost.php?p=18114&postcount=1

The final implemenation mostly matches what's described in the link. It mainly involves in the following steps

- obtain an COleDataSource object from the image file using certain APIs

- retrieve COleDataObject from COleDataSource

- create COleClientItem from COleDataObject

- put the COleClientItem on clipboard (to mimic the process of manual copy of image object to AutoCAD)

- enumerate the binary data items from the clipboard and pass them as a compound document to Teigha by calling setCompoundDocument on its OdDbOle2Frame object

The link above suggested creating a static OLE data object from COleDataSource would be fine, which I muddled through and got work with the code below,

// The  method of creating a compound document for a static OLE object from a picture filevoid CreateStaticOleCompoundDocument(){    HANDLE hDibCopy = CreateDibFromBmp("c:\\temp\\garbage\\sample.bmp");    COleDataSource src;    src.CacheGlobalData(CF_DIB, hDibCopy);    LPDATAOBJECT lpDataObject = (LPDATAOBJECT)src.GetInterface(&IID_IDataObject);    COleDataObject obj;    obj.Attach(lpDataObject);    COleDocument doc;    COleClientItem item(&doc);    item.CreateStaticFromData(&obj);    item.CopyToClipboard();    COleDataObject objReceiver;    if (objReceiver.AttachClipboard())    {        objReceiver.EnsureClipboardObject();                objReceiver.BeginEnumFormats();        FORMATETC format;        FILE *fp;        fopen_s(&fp, "c:\\temp\\garbage\\olestatic.bin", "wb");        while (objReceiver.GetNextFormat(&format))        {            HGLOBAL hmem = objReceiver.GetGlobalData(format.cfFormat);            int size = ::GlobalSize(hmem);            byte *pdata = (byte *)::GlobalLock(hmem);            fwrite(pdata, 1, size, fp);            ::GlobalUnlock(hmem);        }                fclose(fp);    }    obj.Detach();    objReceiver.Release();}

The bin file will be fed to the Teigha through invocation on its setCompoundDocument

To make it work the image has to be converted to a DIB (Device Independent Bitmap) which is given by the code below as a simplified approach,

// references: // http://www.codeguru.com/cpp/g-m/bitmap/article.php/c1693/Creating-a-DIB-section-from-a-BMP-file.htmHGLOBAL CreateDibFromBmp(char *filename){    FILE *fp;    fopen_s(&fp, filename, "rb");    fseek(fp, 0, SEEK_END);    int flen = ftell(fp);    fseek(fp, 0, SEEK_SET);    byte *buf = new byte[flen];    fread(buf, 1, flen, fp);    // this simplified version just takes off the header of the BMP to turn it into DIB    HGLOBAL hmem = ::GlobalAlloc(GMEM_MOVEABLE, flen - 14);    byte *pdib = (byte*)::GlobalLock(hmem);    memcpy(pdib, buf+14, flen-14);    ::GlobalUnlock(hmem);    delete[] buf;    fclose(fp);    return hmem;}

Unfortunately this solution however reasonable it looks doesn't work out well at all, the first and foremost issue it has is the recent versions of AutoCAD show it as a white placeholder for image and upon editing the placeholder object an error message is popped up saying it's a static ActiveX object and is unable to be activated. And it is truly a static ActiveX as is clearly indicated by the subroutine that is used to create a COleClientItem. And that subroutine cannot be replaced by CreateFromData() simply because the way the data object is created from the picture file doesn't allow that.

So I had to find another way which apparently as suggested by the error message has to be creating a non-static OLE object. Hours of effort with alternate attempts for other possibilities was committed and the final solution was inspired by a link http://support.microsoft.com/kb/220844 but not in the same flavour as I couldn't figure out a way to get a simple graft of the Win32 approach to the OLE objects manipulation that follows to work. Below is my current approach,

// The method of creating a compound document for an OLE from a picture filevoid CreateNonStaticCompoundDocument(){    *(&afxCurrentAppName) = L"testapp";    COleDocument doc;    COleClientItem item(&doc);    item.CreateFromFile(L"C:\\temp\\garbage\\sample.bmp");    item.CopyToClipboard();    COleDataObject objReceiver;    if (objReceiver.AttachClipboard())    {        objReceiver.EnsureClipboardObject();                objReceiver.BeginEnumFormats();        FORMATETC format;        FILE *fp;        fopen_s(&fp, "c:\\temp\\garbage\\olenonstatic.bin", "wb");        while (objReceiver.GetNextFormat(&format))        {            HGLOBAL hmem = objReceiver.GetGlobalData(format.cfFormat);            int size = ::GlobalSize(hmem);            byte *pdata = (byte *)::GlobalLock(hmem);            fwrite(pdata, 1, size, fp);            ::GlobalUnlock(hmem);        }                fclose(fp);    }    objReceiver.Release();}

The above approach brings me much closer to the goal. Although it still just creates a white box with no sign of image but AutoCAD doesn't complain when the user is trying to open the OLE and it does show the right image in the paintbrush application.

Note both of the above approaches preserve the data fine as one can copy paste image from AutoCAD.

It can be obviously see how awkward OLE/COM technologies are (I suppose I might have missed some COM object finalisation). They may provide some runtime performance benefit and extensibility, however it's far less productive than .NET and the performance is not that much at all if .NET and its interoperability are optimally used. And I see products using this kind of technology as well as MFC/ATL such as AutoCAD etc. for most part of it including the architecture just because they've long been used rather than they are necessary.