Why does windows let you draw on the whole screen? - c++

I've been playing a big with the DC obtained with CreateDC(L"DISPLAY",NULL,NULL,NULL) and I've been wondering why does windows let you draw on the whole screen that easily, cause I think you could do some pretty evil stuff with that like putting a TIMER at 1ms and drawing a black rectangle on the whole screen every time the timer ticks.

The fact that you could do some pretty evil stuff doesn't mean windows shouldn't let you do it. Just think of all the other evil things you could do:
Run in an infinite loop and eat up all the cpu time.
Write random bits to a file until you fill up the whole hard disk.
Delete random files all over the place.
Allocate memory like crazy until the computer slows to a crawl.
Just because you CAN do those things doesn't mean windows should prevent you from writing to the hard drive or allocating memory or deleting files.
The purpose of Windows is to provide an environment in which programs can run. The more flexible they make that environment, the more interesting (and, unfortunately, devious) programs it makes possible for developers to create.
If they started putting in arbitrary restrictions on what you can do because you might abuse it... well, then it wouldn't be windows, it would be an iPhone :)

why does windows let you write to the hard drive so easily?
you could do some pretty evil stuff like overwrite every file on the hard drive.

The security of the desktop is given to the user running the desktop, you can't draw on it if you are not a privileged user.
Note that one doesn't usually CreateDC() on the desktop, but usually GetDC() for a particular window during the WM_PAINT message handler.
A program can also delete the file system, or destroy the registry (if suitably permissioned), the desktop is a user-permissioned resource like any other. If they run an application with their security credentials, they can do what they wish.
However in practice, one would create a window and paint within it.

Because it should be that easy.
It is that easy because to put rules and controls in place would mean that you would be cutting down the things you can do with the language and the windows framework. If this happened then there would be screams from the other side of the fence shouting at how you can't do this and that.
It is these abilities which make the language powerful, but with that power comes the danger. Just because you can do something, doesn't mean that you should. You can format you hard drive... doesn't mean that you should do this when you launch the clock application.
If you are not happy with this level of 'responsibility' then pick a different language or framework to write in.

Everything is a Window and Every Window has a HANDLE. So, if you have got DesktopHandle, then you can draw anything on it. What is the problem with it.
Offcourse, the application that is doing evil stuff(like you said) has been allowed to run on the machine by yourself, therefore, it can do more eviler stuff than this such as formatting your hard-drive etc.

If the method you're using (getting the screen DC) was disabled, it wouldn't stop people from doing the following.
You can create a window, you can paint in the window, you can set the size of the window to cover the whole screen, therefore you can paint on the whole screen.
And you can grab a bitmap of the whole screen, so you can paint the underlying screen content in the window and then make adjustments to it.
So it would be very easy to simulate the same effect using a combination of things that, on their own, are perfectly valid and extremely useful.

Because there may be a time when you need to do these things. I am sure at the moment you can't think of any but writing on the screen may be useful.
On OS X there are many applications who write directly on the screen. Useful information like CPU time or even a calender. That's cool!
But not everything that can be done must be done.

One of the primary reasons Windows is so afflicted with malware is the lack of security around such things as you describe. Others have cited examples such as filling the hard drive, erasing random files, or eating CPU time... all of these things are security concerns, and all of them are prevented by the other two major operating systems (Linux and OSX). This doesn't mean that you can't do similar things on those operating systems, but it means that a normal user can't do it. They'd have to be granted the right permissions, and usually also forced to use a very restrictive API to limit what they can do. So the answer to your question is "because it wasn't designed with security in mind". This allows programmers significantly more flexibility, and these powers can be used for good, but IMHO it more often breeds laziness (people use the brute force way instead of spending the time figuring out the "right" way to do something) and opens the door for security problems (malware).

Related

Shutting down fan c++ [duplicate]

Is there a Windows standard way to do things such as "start fan", "decrease speed" or the like, from C/C++?
I have a suspicion it might be ACPI, but I am a frail mortal and cannot read that kind of documentation.
Edit: e.g. Windows 7 lets you select in your power plan options such as "passive cooling" (only when things get hot?) vs. "active cooling" (keep the CPU proactively cool?). It seems the OS does have a way to control the fan generically.
I am at the moment working on a project that, among other things, controls the computer fans. Basically, the fans are controlled by the superIO chip of your computer. We access the chip directly using port-mapped IO, and from there we can get to the logical fan device. Using port-mapped IO requires the code to run in kernel mode, but windows does not supply any drivers for generic port IO (with good reason, since it is a very powerful tool), so we wrote our own driver, and used that.
If you want to go down this route, you basically need knowledge in two areas: driver development and how to access and interpret superIO chip information. When we started the project, we didn't know anything in either of these areas, so it has been learning by browsing, reading and finally doing. To gain the knowledge, we have been especially helped by looking at these links:
The WDK, which is the Windows Driver Kit. You need this to compile any driver you write for windows, With it comes a whole lot of source code for example drivers, including a driver for general port-mapped IO, called portio.
WinIO has source code for a driver in C, a dll in C that programmatically installs and loads that driver, and some C# code for a GUI, that loads the dll and reads/writes to the ports. The driver is very similar to the one in portio.
lm-sensors is a linux project, that, among other things, detects your superIO chip. /prog/detect/sensors-detect is the perl program, that does the detecting, and we have spent some time going through the code to see how to interface with a superIO chip.
When we were going through the lm-sensors code, it was very nice to have tools like RapidDriver and RW-everything, since they allowed us to simulate a run of sensors-detect. The latter is the more powerful, and is very helpful in visualising the IO space, while the former provides easier access to some operations which map better to the ones in sensors-detect (read/write byte to port)
Finally, you need to find the datasheet of your superIO chip. From the examples, that I have seen, the environment controllers of each chip provide similar functionality (r/w fan speed, read temperature, read chip voltage), but vary in what registers you have to write to in order to get to this functionality. This place has had all the datasheets, we have needed so far.
If you want something real quick to just lower fans to a level where you know things won't overheat, there's the speedfan program to do so. Figuring out how to configure it in the early versions to automatically lower fans to 50% on computer startup was so painful that my first approach was to simply byte-patch it to start the only superio managed fan I had at lower speed. The newer versions are still bit tough but it's doable - there's a graphical slider system that looks like audio equalizer except that the x axis is temp and y is fan speed. You drag them down one by one. After you figure out how to get manual control for the fan you want, this is next step.
There's a project to monitor hardware (like fans) with C#:
http://code.google.com/p/open-hardware-monitor/
I haven't extensively looked at it, but the source code and use of WinRing0.sys atleast gives the impression that if you know what fan controller you have and have the datasheet, it should be modifiable to also set values instead of just getting them. I don't know what tool is suited (beside kernel debugger) to look at what Speedfan does, if you preferred to snoop around and imitate speedfan instead of looking at the datasheets and trying things out.
Yes, It would be ACPI, and to my knowledge windows doesn't give much/any control over that from user space. So you'd have to start mucking with drivers, which is nigh impossible on windows.
That said, google reveals there are a few open source windows libraries for this for specific hardware... so depending on your hardware you might be able to find something.
ACPI may or may not allow you to adjust the fan settings. Some BIOS implementations may not allow that control though -- they may force control depending on the BIOS/CMOS settings. One might be hard-pressed for a good use case where the BIOS control (even customized) is insufficient. I have come across situations where the BIOS control indeed was insufficient, but not for all possible motherboard platforms.
WIndows Management Instrumentation library (WMI) does provide a Win32_Fan Class and even a SetSpeed method. Alas, the docs say this is not implemented, so I guess it's not very helpful. But you may be able to control things by setting the power state.

Move Window Linux C

i'd like to make a function that can move a window in Linux in C++ by its PID. So I've tryed in under Windows. But I have trouble to compile it for Linux.
Is there any mean to do it with Qt ? Since I haven't found one, I've tryed to compile for Linux.
I'm using the MoveWindow function, which is part of the Windows API. Is there any Linux equivalent ?
You don't have to do that by hand if you don't really want to as there already are lots of tools out there, that can perform such tasks as moving, resizing, maximizing and whatever windows.
One tool you might want to take a closer look upon goes by the name of wmctrl even if you don't intend to use maybe you'll find some interesting tricks by taking a look into the sources.
The task of moving a window only known by the pid of the client that created the window might not be the easiest tasks of all for a couple of reasons.
First of all you really shouldn't try to do this as in the X Windows philosophy it is the job of the window manager to arrange the windows on the screen.
As well ICCCM (see: http://de.wikipedia.org/wiki/Inter-Client_Communication_Conventions_Manual) as the EWM spec (see: http://standards.freedesktop.org/wm-spec/wm-spec-latest.html) strongly discourage any client from trying to move resize or whatever on its own. Most probably moving windows "owned" by another client might be considered even bigger evil.
The second problem you might face is, that the X 11 protocol doesn't have any notion of pid.
As it was designed to be used over a network you never can't be really sure the program runs on the same machine as the one you are currently sitting in front of. As such there isn't much sense in something like a pid as by chance there might be any number of clients with identical pids displaying windows on the same X Server if they ran on different machines.
Fortunately enough it is not all that bad, as the EWMH spec encourages any client to set the _NET_WM_PID property on its top level window the the pid of the client that created the window.
Again adhering to the EWMH spec isn't enforced by the X Server in any way so that while practically propably almost all clients will set it there's still no guarantee you'll find the window belonging to a specific pid.
Possibilities
While the whole points mentioned until here might seem rather limiting in fact most probably rather the opposite is true. Even because practically it is relatively easy to totally mess up any other client running in an X session the whole set of rules about how to be a good citizen in the X word were introduced.
As the X11 protocol itself is a network protocol (well not 100% true as locally running clients most probably will be communicating with the X Server via a UNIX domain socket) there isn't any specific library required to talk to the X Server.
Talking about C as mentioned in your question the Xlib has long been the one and only one implementation in wide use but there's also another binding called xcb. With a slightly changed API in comparison to the Xlib.
Xlib
Speaking Xlib I've never ever used any xcb until now, so I can't tell you too much about it might be the following methods that might be of use.
XOpenDisplay - open connection to the X server
XQueryTree - aquire the tree of windows currently alive on the server
XInternAtom - no fear it isn't dangerous. Just read about it in the manuals as you'll need it the get the "atom" mapping to _NET_WM_PID mentioned above
XListProperties - search for the _NET_WM_PID property with the value you are looking for
XConfigureWindow, XMoveWindow, XResizeWindow, ... - to finally perform whatever you wish to do.
All functions mentioned above should be documented in the manual pages. Just use man XOpenDisplay for example.
Oh, and be sure to learn about all the other tools at your disposal to further investigate about the X Window world. Run xlsatoms, check what xwininfo reports an take a list at the output of xprop for one single (!) window alone. Try to set some yourself to see what happens xprop will even do that for you if you ask politely.

Qt Application Performance vs. WinAPI/MFC/WTL/

I'm considering writing a new Windows GUI app, where one of the requirements is that the app must be very responsive, quick to load, and have a light memory footprint.
I've used WTL for previous apps I've built with this type of requirement, but as I use .NET all the time in my day job WTL is getting more and more painful to go back to. I'm not interested in using .NET for this app, as I still find the performance of larger .NET UIs lacking, but I am interested in using a better C++ framework for the UI - like Qt.
What I want to be sure of before starting is that I'm not going to regret this on the performance front.
So: Is Qt fast?
I'll try and qualify the question by examples of what I'd like to come close to matching: My current WTL app is Programmer's Notepad. The current version I'm working on weighs in at about 4mb of code for a 32-bit, release compiled version with a single language translation. On a modern fast PC it takes 1-3 seconds to load, which is important as people fire it up often to avoid IDEs etc. The memory footprint is usually 12-20 mb on 64-bit Win7 once you've been editing for a while. You can run the app non-stop, leave it minimized, whatever and it always jumps to attention instantly when you switch to it.
For the sake of argument let's say I want to port my WTL app to Qt for potential future cross-platform support and/or the much easier UI framework. I want to come close to if not match this level of performance with Qt.
Just chiming in with my experience in case you still haven't solved it or anyone else is looking for more experience. I've recently developed a pretty heavy (regular QGraphicsView, OpenGL QGraphicsView, QtSQL database access, ...) application with Qt 4.7 AND I'm also a stickler for performance. That includes startup performance of course, I like my applications to show up nearly instantly, so I spend quite a bit of time on that.
Speed: Fantastic, I have no complaints. My heavy app that needs to instantiate at least 100 widgets on startup alone (granted, a lot of those are QLabels) starts up in a split second (I don't notice any delay between doubleclicking and the window appearing).
Memory: This is the bad part, Qt with many subsystems in my experience does use a noticeable amount of memory. Then again this does count for the many subsystems usage, QtXML, QtOpenGL, QtSQL, QtSVG, you name it, I use it. My current application at startup manages to use about 50 MB but it starts up lightning fast and responds swiftly as well
Ease of programming / API: Qt is an absolute joy to use, from its containers to its widget classes to its modules. All the while making memory management easy (QObject) system and mantaining super performance. I've always written pure win32 before this and I wil never go back. For example, with the QtConcurrent classes I was able to change a method invocation from myMethod(arguments) to QtConcurrent::run(this, MyClass::myMethod, arguments)and with one single line a non-GUI heavy processing method was threaded. With a QFuture and QFutureWatcher I could monitor when the thread had ended (either with signals or just method checking). What ease of use! Very elegant design all around.
So in retrospect: very good performance (including app startup), quite high memory usage if many submodules are used, fantastic API and possibilities, cross-platform
Going native API is the most performant choice by definition - anything other than that is a wrapper around native API.
What exactly do you expect to be the performance bottleneck? Any strict numbers? Honestly, vague ,,very responsive, quick to load, and have a light memory footprint'' sounds like a requirement gathering bug to me. Performance is often overspecified.
To the point:
Qt's signal-slot mechanism is really fast. It's statically typed and translates with MOC to quite simple slot method calls.
Qt offers nice multithreading support, so that you can have responsive GUI in one thread and whatever else in other threads without much hassle. That might work.
Programmer's Notepad is an text editor which uses Scintilla as the text editing core component and WTL as UI library.
JuffEd is a text editor which uses QScintilla as the text editing core component and Qt as UI library.
I have installed the latest versions of Programmer's Notepad and JuffEd and studied the memory footprint of both editors by using Process Explorer.
Empty file:
- juffed.exe Private Bytes: 4,532K Virtual Size: 56,288K
- pn.exe Private Bytes: 6,316K Virtual Size: 57,268K
"wtl\Include\atlctrls.h" (264K, ~10.000 lines, scrolled from beginning to end a few times):
- juffed.exe Private Bytes: 7,964K Virtual Size: 62,640K
- pn.exe Private Bytes: 7,480K Virtual Size: 63,180K
after a select all (Ctrl-A), cut (Ctrl-X) and paste (Ctrl-V)
- juffed.exe Private Bytes: 8,488K Virtual Size: 66,700K
- pn.exe Private Bytes: 8,580K Virtual Size: 63,712K
Note that while scrolling (Pg Down / Pg Up pressed) JuffEd seemed to eat more CPU than Programmer's Notepad.
Combined exe and dll sizes:
- juffed.exe QtXml4.dll QtGui4.dll QtCore4.dll qscintilla2.dll mingwm10.dll libjuff.dll 14Mb
- pn.exe SciLexer.dll msvcr80.dll msvcp80.dll msvcm80.dll libexpat.dll ctagsnavigator.dll pnse.dll 4.77 Mb
The above comparison is not fair because JuffEd was not compiled with Visual Studio 2005, which should generate smaller binaries.
We have been using Qt for multiple years now, developing a good size UI application with various elements in the UI, including a 3D window. Whenever we hit a major slowdown in app performance it is usually our fault (we do a lot of database access) and not the UIs.
They have done a lot of work over the last years to speed up drawing (this is where most of the time is spent). In general unless you really do implement a kind of editor usually there is not a lot of time spent executing code inside the UI. It mostly waits on input from the user.
Qt is a very nice framework, but there is a performance penalty. This has mostly to do with painting. Qt uses its own renderer for painting everything - text, rectangles, you name it... To the underlying window system every Qt application looks like a single window with a big bitmap inside. No nested windows, no nothing. This is good for flicker-free rendering and maximum control over the painting, but this comes at the price of completely forgoing any possibility for hardware acceleration. Hardware acceleration is still noticeable nowadays, e.g. when filling large rectangles in a single color, as is often the case in windowing systems.
That said, Qt is "fast enough" in almost all cases.
I mostly notice slowness when running on a Macbook whose CPU fan is very sensitive and will come to life after only a few seconds of moderate CPU activity. Using the mouse to scroll around in a Qt application loads the CPU a lot more than scrolling around in a native application. The same goes for resizing windows.
As I said, Qt is fast enough but if increased battery draining matters to you, or if you care about very smooth window resizing, then you don't have much choice besides going native.
Since you seem to consider a 3 second application startup "fast", it doesn't sound like you would care at all about Qt's performance, though. I would consider 3 second startup dog-slow, but opinions on that vary naturally.
The overall program performance will of course be up to you, but I don't think that you have to worry about the UI. Thanks to the graphics scene and OpenGL support you can do fast 2D/3D graphics too.
Last but not least, an example from my own experience:
Using Qt on Linux/Embedded XP machine with 128 MB of Ram. Windows uses MFC, Linux uses Qt. Custom user GUI with lots of painting, and a regular admin GUI with controls/widgets. From a user's point of view, Qt is as fast as MFC. Note: it was a full screen program that could not be minimized.
Edited after you have added more info:
you can expect a larger executable size (especially with Qt MinGW) and more memory usage. In your case, try playing with one of the IDEs (e.g. Qt Creator) or text editors written in Qt and see what you think.
I personally would choose Qt as I've never seen any performance hit for using it. That said, you can get a little closer to native with wxWidgets and still have a cross-platform app. You'll never be quite as fast as straight Win32 or MFC (and family) but you gain a multi-platform audience. So the question for you is, is this worth a small trade-off?
My experience is mostly with MFC, and more recently with C#. MFC is pretty close to the bare metal so unless you define a ton of data structure, it should be pretty quick.
For graphics painting, I always find it useful to render to a memory bitmap, and then blt that to the screen. It looks faster, and it may even be faster, because it's not worrying about clipping.
There usually is some kind of performance problem that creeps in, in spite of my trying to avoid it. I use a very simple way to find these problems: just wait until it's being subjectively slow, pause it, and examine the call stack. I do this a number of times - 10 is usually more than enough. It's a poor man's profiler but works well, no fuss, no bother. The problem is always something no one could have guessed, and usually easy to fix. This is why it works.
If there are dialogs of any complexity, I use my own technique, Dynamic Dialogs, because I'm spoiled. They are not for the faint-of-heart, but are very flexible and perform nicely.
I once made an app to determine the "primeness" of a number (whether it was prime or composite).
I first attempted a Qt GUI, and it took 5 hours to return the answer for 1,299,827 on a computer with 8GB of RAM and an AMD 1090T # 4GHz running no other foreground processes under Linux.
My second attempt used a QProcess of a console application that used the exact same code. On a laptop with 1.3GB of RAM and a 1.4GHz CPU, the response came with no perceivable delay.
I will not deny, though, that it is far easier than GTK+ or Win32, and it handles things quite nicely, but separate intensive processing ENTIRELY from the GUI if you use it.

How do I detect desktop transition effects?

I want to minimise my application, take a screenshot of the current desktop and return my application back to its original state.
This has been working fine under windows XP, however under testing on different Vista machines the minimise time of 200 milliseconds is no longer valid.
Is there a way to ask the operating system when it has finished these fancy effects or lookup how long it has been given to perform the operation?
While I don't know of a way to do what you ask, I have a suggestion: instead of minimizing your application's window, why not hide it (with ShowWindow(SW_HIDE))? That will not be subject to the animation effects, so should be pretty much instantaneous.
Maybe instead minimizing you should bring desktop to front?
The closest I can find is SPI_GETUIEFFECTS, which tells you if such effects are enabled at all.
If enabled, you could of course use SPI_SETUIEFFECTS to turn them off. But that's a rather shotgun method - how would you restore them? It's probably better to temporarily turn off the ones that bother you most.

How can I code my own custom splash screen for Linux?

This is NOT a question on plain old boring customization; I actually want to create an program, you know, with source code, etc...
I'm thinking about programming my own media centre interface, and I figured it'd look better if I coded my own splash screen for when the OS is loading.
Note: The media centre interface will be run in X, but this question is regarding what will happen before the X server loads.
Simply, I'd like to make a splash screen application to hide the linux kernel boot messages. Is there a way I can program some animation in to this like some sort of animated progress bar for example? I assume that I won't be able to code any 2D/3D graphics (as that'd require X to be running, right?), so how would I go about generating that?
I'd prefer to do this in C++, but C is also an option.
Note: I'm not looking to use any existing "themes" or anything like that, just interested in the programming side of things.
Update:
Some suggestions have been to use standard images (.bmp, .jpeg, etc), I am not interested in loading images in to an existing application. But obviously I may want to load images in to the boot screen application that I will make.
I'm not tied to a Linux distro, so this can be for anything, although Debian or a Debian-based distro would be nice.
I like the suggestion about loading the X server early and running a loading screen from there, however is there not a more direct approach? Surely you can make a program which hides the boot messages and shows a custom program? Obviously this would be very low level programming, but that's what I'm looking for...
Also, I'm not interested in altering the boot loader (LILO, GRUB, etc).
Update 2:
So far good suggestions have been looking at the source code for applications like splashy and fbsplash. Can anyone better this suggestion?
For the graphical output you can use the Linux framebuffer, for application development you can use gtk which support rendering directly to the framebuffer GtkFB.
For the video and such you can use mplayer which also support rendering to the framebuffer.
For the initialization you have to look around the system used, debian uses a sysv init style initialization http://www.debian-administration.org/articles/212, ubuntu uses upstart.
I'd look into splashy source code. But you will need to code in C.
If you have the skills, you can implement a software based 3D engine (like in the good old days). A simple rotating cube shouldn't be very hard to code and there are tons of tutorials.
The downside is that you will increase the boot time, something not very pleasant in a media center.
Here's the thing: there is a library/kernel patch, fbsplash, that has already been written to do exactly what it sounds like you want to do. It will display an image in place of the normal boot messages, and it can also incorporate a progress bar. When you're trying to do something for which a well-established open-source implementation already exists, there's really no better way to learn how to do it yourself than to look at the source code.
Even if you're looking for something more complicated (say if you want to create some fancier animation than a progress bar), you might be able to start with fbsplash and modify it to suit your needs.
There are several ways you could do this. You could have the X server load very early, and just write a program to display the splash screen. You could also use the framebuffer device. If you are using Intel hardware, or are willing to use the OSS AMD drivers, or Nouveau for Nvidia, you could use kernel mode setting. For this, I would look at Fedora's Plymouth. You could just write a Plymouth plugin to display your splash screen.
The splash screen is simply an image (.bmp, .jpg, etc.) and can be loaded by the boot loader. Since you haven't specified the distribution you're using, look into LILO, grub, or whichever one is appropriate. Check the /boot directory for clues that will direct your search.
If all you want to do is have a nice clean boot sequence with your own splash and absolutely no boot messaging you can do the following:
First, silence grub, boot messaging, and console cursor:
GRUB_CMDLINE_LINUX_DEFAULT = quiet fastboot splash vt.cur_default=1 loglevel=0
GRUB_TIMEOUT = 0
This will very quickly and silently (fade to black) bring you to your login screen, where you can place a splash. Your distro may show it's own splash briefly, which you can change if you like.
This yeilds a professional clean boot sequence, without all the usual linux warts and wrinkles. (Like OSX and Windows).
I personally use Ubunutu with LXDE, and have a clean splashy boot in under 3 seconds, even on older hardware.