Using console in VCL applications - c++builder

Is there a way for using the console for output in VCL applications? Where does cout actually direct the stream in VCL applications?

I did it as follows:
void TForm1::Button1Click(TObject *Sender)
{
out_to_console("Some text\n");
}
void out_to_console(std::string str)
{
AllocConsole() ;
AttachConsole(GetCurrentProcessId()) ;
std::freopen("CON", "w", stdout) ;
std::cout<<str;
}
Two questions still remain for me open:
Why I need the escape sequence \n to see the text Some text on the console?
Where does stdoutpoint to in VCL applications?

Related

Read text from an URL on Codename One

I'm relatively new to codename one. I'm trying to read text from a pure text url and store the text in a string. I tried using the java IO package but for some reason it doesn't seem to wirk with codename one. Please help.
David.
I think you might not really understand codenameone seeing as you tried to use the Java IO package. But anyway, this code might get you along
ConnectionRequest r = new ConnectionRequest();
r.setUrl("YOURURLHERE");
r.setPost(false);
r.addResponseListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
NetworkEvent event = (NetworkEvent) ev;
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
System.out.println(decodedData);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
});
NetworkManager.getInstance().addToQueue(r);
NOTE: Instead of using System.out.println, which works fine for debugging purposes, you probably want to add the text to your application with a GUI component. I'm not sure if this needs to be said, but it won't do any harm stating it again :)

C++ Builder 2010 Strange Access Violations

I've got a program that is to become part of an already existing, larger product which is built using C++ Builder 2010.
The smaller program does not (yet) depend on C++ Builder. It works fine in MS Visual Studio, but with C++ Builder it produces strange access violations.
Please let me explain this.
Depending on the code and on compiler settings, access violations happen or do not happen. The access violations are reproducible: When the program is built then the access violation does never occur or it does always occur at the same place. If the program is rebuilt with the same settings, it will show the same behavior. (I'm really glad about that).
The access violation happens at places where the delete operator is called. This can happen (depending on compiler settings and exact code) inside certain destructors, including destructors of own classes and inside the destructor of std::string.
The following things make the access violation less likely:
Build with "Debug" settings (instead of "Release").
No compiler optimizations.
Compiler switch "Slow exception epilogues".
Static RTL instead of dynamic.
Derive exceptions from std::exception instead of Borland's Exception class.
Use less "complicated" expressions (e.g. use "string s = "..." + "..."; throw SomeException(s);" instead of "throw
SomeException(string("...") + "...");")
Use try... __finally with manual cleanup instead of automatic variables with destructors.
Use a small console application instead a VCL windows application.
The program makes use of several C++ features, including exceptions, STL, move constructors etc. and it of course uses the heap.
I already tried some tools, none of them reported problems:
Borland's CodeGuard.
Microsoft Application Verifyer.
pageheap/gflags.
As already mentioned, there is absolutely no problem when building with MS Visual Studio.
Use of precompiled headers and incremental linking (which both seem to me are prone to errors) are disabled.
Neither the C++ Builder compiler ("enable all warnings") nor the one of Visual Studio (/W4) produces a warning that might be related to this issue.
I do not have access to another version of C++ Builder.
As the program will become part of a larger product, it is not an option to switch to a different compiler, and it is not an option to tune the compiler settings until the access violation does no longer happen. (I fear if this really should a compiler bug, the bug might show up again.)
Putting this together, I'm guessing this might result from heap corruption that is related to some compiler bug. However, I was not able to find a bug on qc.embarcadero.com. I'm guessing further this is related to cleanup code that is executed upon stack rewinding when an exception has been thrown. But, well, maybe it's only a stupid code bug.
Currently, I do not have any idea how to proceed. Any help appreciated. Thank you in advance!
tl;dr I believe the bug is that code is generated to delete the std::string from both branches of the ternary operator during stack unwinding, however only one of them was actually created of course.
Here is a simpler MCVE, which shows the problem via outputs in XE5:
#include <vcl.h>
#include <tchar.h>
#include <stdio.h>
using namespace std;
struct S
{
S() { printf("Create: %p\n", this); }
S(S const &) { printf("Copy: %p\n", this); }
void operator=(S const &) { printf("Assign: %p\n", this); }
~S() { printf("Destroy: %p\n", this); }
char const *c_str() { return "xx"; }
};
S rX() { return S(); }
int foo() { return 2; }
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
try
{
throw Exception( (foo() ? rX() : rX()).c_str() );
}
catch (const Exception& e)
{
}
getchar();
return 0;
}
This version shows the problem via output strings on the console. Check the edit history for this post to see a version that uses std::string and causes the segfault instead.
My output is:
Create: 0018FF38
Destroy: 0018FF2C
Destroy: 0018FF38
In the original code, the segfault comes from the bogus Destroy ending up calling delete on the bogus value it obtains by trying to retrieve the internal data pointer for a std::string which was actually never created at that location.
My conjecture is that the code generation for stack unwinding is bugged and tries to delete the temporary string from both branches of the ternary operator. The presence of the temporary UnicodeString does have something to do with it; as the bug did not occur in any variations where I tried to avoid that temporary.
In the debugger you can see the call stack and it is during global stack unwinding that this happens.
Phew, that was so simple that it took me some time:
#include <vcl.h>
#include <tchar.h>
#include <string>
using namespace std;
struct B
{
B(const char* c) { }
string X() const { return "xx"; }
int Length() const { return 2; }
};
struct C
{
void ViolateAccess(const B& r)
{
try
{
throw Exception(string("aoei").c_str());
}
catch (const Exception&) { }
throw Exception(((string) "a" + (r.Length() < 10 ? r.X() : r.X() + "...") + "b").c_str());
}
};
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
try
{
C c;
c.ViolateAccess("11");
}
catch (const Exception& e) { }
return 0;
}
(Preemptive comment: No, this code does not make any sense.)
Create a new console application and make sure to use the VCL. It might depend on the project settings whether there will be an access violation or not; my debug builds always crashed, release builds didn't.
Crashes with C++ Builder 2010 and XE3 trial.
Thus, bug in compiler or in VCL or in STL or whatever.

TypeScript localization issues

If I use typescript and declare a string there, and set that string to some Russian text.
Then typescript compiler compiles to JavaScript with no regard to encoding I use in solution.
So I get that "questions in rombic symbols" instead of normal letters.
So, do you know how to fix it?
TypeScript as default creates an ANSI encoded file when added using visual studio. (or visual studio creates ansi files as standard)
To fix open the file in notepad and use "save as" and change the encoding to UTF8 or UNICODE.
You need to change your file encoding to UNICODE.
Compiling:
var x = "привет мир";
class foo {
public done() {
return "привет мир";
}
}
Gave the following JS for me:
var x = "привет мир";
var foo = (function () {
function foo() { }
foo.prototype.done = function () {
return "привет мир";
};
return foo;
})();
I have the same issue when I use cscript to run tsc.js compiler.
I've found that the input file for tsc should be in utf-8 with signature (BOM) or unicode-16 encoding.
If I use nodejs to run tsc.js the input file could be in utf-8 even without signature and everything is ok.

What do I need to know to create a source code editor?

Say I want to create a source code editor for ocaml programming language, where do I start? I am looking to create an editor for the Windows platform as a hobby project. My primary skill is in web development. I have developed windows apps long time ago. I have no clue how it is done with todays available tools. I have visual studio 2008 and C# is my language of choice.
You need to know:
OCAML Syntax, Features, Keywords, Functions etc...
C# as this is your native language I guess
You need to know what features you wanna implement
...if it's using a GUI or just from a terminal like nano/vim
how syntax highlighting works
how to open and save files
how autocompletion works
etc..
You might want to take look at some open source editors like dev-c++ or gedit
Also, as you in person are more web-devvy, you might want to start creating one which runs in a web browser. This is often easier and helps you understand the basics of creating a code editor. Later you can always write one for desktops.
If you are most comfortable in Visual Studio, then you can use the Visual Studio Shell to create your own IDE based on that foundation.
Here is a podcast that gives a good overview:
http://www.code-magazine.com/codecast/index.aspx?messageid=32b9401a-140d-4acb-95bb-6accd3a3dafc
Also, as a reference, the IronPython Studio was created using the Visual Studio 2008 Shell:
http://ironpythonstudio.codeplex.com/
Browsing that source code should give you a good starting point.
a lighter-weight alternative is to use the RichEdit control
example:
http://www.codeproject.com/Messages/3401956/NET-Richedit-Control.aspx
// http://www.codeproject.com/Messages/3401956/NET-Richedit-Control.aspx
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace RichEditor
{
public class RichTextBoxEx : RichTextBox
{
IntPtr mHandle = IntPtr.Zero;
protected override CreateParams CreateParams
{
get
{
// Prevent module being loaded multiple times.
if (this.mHandle == IntPtr.Zero)
{
// load the library to obtain an instance of the RichEdit50 class.
this.mHandle = LoadLibrary("msftedit.dll");
}
// If module loaded, reset ClassName.
if (this.mHandle != IntPtr.Zero)
{
CreateParams cParams = base.CreateParams;
// Check Unicode or ANSI system and set appropriate ClassName.
if (Marshal.SystemDefaultCharSize == 1)
{
cParams.ClassName = "RichEdit50A";
}
else
{
cParams.ClassName = "RichEdit50W";
}
return cParams;
}
else // Module wasnt loaded, return default .NET RichEdit20 CreateParams.
{
return base.CreateParams;
}
}
}
~RichTextBoxEx()
{
//Free loaded Library.
if (mHandle != IntPtr.Zero)
{
FreeLibrary(mHandle);
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadLibrary(String lpFileName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);
}
}
You could use Scintilla. It has syntax highlighting and some other features. Also, it has a .NET Version available here.
Another good tool is Alsing Syntax Box:
Powerful Syntax Highlight Windows
Forms Control for the Microsoft.NET
Platform. Written in 100% managed C#.
Supports syntax highlighting and code
folding for just about any programming
language.
With Alsing Syntax Box, you can define a syntax file (just like this one for C#) and later have a intellisense like feature.
You can start with one of them for your editor.

HTML Editor for CBuilder/Delphi

I need to find basic WYSIWYG HTML editor component for C++Builder 5 to let users to create some simple text that I will paste into existing HTML page template.
Just a simple support to create links, add images, use headers/bold/italic.
You can drop a TWebBrowser on a form and enable designmode on it, like this:
// Delphi code..
(WebBrowser1.Document as IHTMLDocument2).designMode := 'on';
After executing the above line, the page will be editable. You can type extra text, delete, etc. If you want to make selections bold or insert images, you're going to have to add some buttons to program that. The cool thing is that you can do that either from Delphi (or C++ builder in your case) or you can add javascript on the page to edit itself.
The contents of the page can be retrieved from
(WebBrowser.Document as IHTMLDocument2).body.innerHTML;
Remember that (WebBrowser.Document as IHTMLDocument2) could be nil.
Anyway, I can imagine that there are components around that do all the work for you, which is probably a better route to take than reinventing the wheel.
I would recommend TRichView due to its world class support, and deep feature set. While it is not a true "HTML" editor, it does support the ability to export to HTML, even generating the appropriate CSS styles if necessary. I use it for handling the email portion of our main product and it works very well. Internally the storage is either RTF (extended to support images better), or as a proprietary format. There are plenty of examples of a simple editors which would easily suit your needs.
in C++ Builder, it would be something like this:
(wb is a TCppWebBrowser)
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "mshtml.h"
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "SHDocVw_OCX"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btnNavigateAndEditClick(TObject *Sender)
{
wb->Navigate((WideString)"www.google.com");
while (wb->Busy)
Application->ProcessMessages();
if (wb->Document)
{
IHTMLDocument2 *html;
wb->Document->QueryInterface<IHTMLDocument2>(&html);
html->put_designMode(L"On");
html->Release();
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btnInsertImageClick(TObject *Sender)
{
if (wb->Document)
{
IHTMLDocument2 *html;
wb->Document->QueryInterface<IHTMLDocument2>(&html);
VARIANT var;
VARIANT_BOOL receive;
html->execCommand(L"InsertImage",true,var, &receive);
html->Release();
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btnGetHtmlClick(TObject *Sender)
{
if (wb->Document)
{
IHTMLDocument2 *html;
wb->Document->QueryInterface<IHTMLDocument2>(&html);
IHTMLElement *pElement;
html->get_body(&pElement);
pElement->get_parentElement(&pElement);
wchar_t *tmp;
pElement->get_outerHTML(&tmp);
Memo1->Lines->Text = tmp;
pElement->Release();
html->Release();
}
}
//---------------------------------------------------------------------------
http://www.bsalsa.com/
supplies a free set of EmbeddedWebBrowser components with an Edit Designer component
that you link to the EmbeddedBrowser window to control design mode and have edit control
save to file, insert links, images, etc...
seems to work well!

Resources