//========================================================================== // The 'main' function for the booter. Called by boot0 when booting // from a block device, or by the network booter. // // arguments: // biosdev - Value passed from boot1/NBP to specify the device // that the booter was loaded from. // // If biosdev is kBIOSDevNetwork, then this function will return if // booting was unsuccessful. This allows the PXE firmware to try the // next boot device on its list. void common_boot(int biosdev) { bool quiet; bool firstRun = true; bool instantMenu; bool rescanPrompt; char *bootFile; int status; unsigned int allowBVFlags = kBVFlagSystemVolume | kBVFlagForeignBoot; unsigned int denyBVFlags = kBVFlagEFISystem; unsigned long adler32; // Set reminder to unload the PXE base code. Neglect to unload // the base code will result in a hang or kernel panic. gUnloadPXEOnExit = true; // Record the device that the booter was loaded from. gBIOSDev = biosdev & kBIOSDevMask; // Initialize boot info structure. initKernBootStruct(); initBooterLog(); // Setup VGA text mode. // Not sure if it is safe to call setVideoMode() before the // config table has been loaded. Call video_mode() instead. #if DEBUG printf("before video_mode\n"); #endif video_mode( 2 ); // 80x25 mono text mode. #if DEBUG printf("after video_mode\n"); #endif // Scan and record the system's hardware information. scan_platform(); // First get info for boot volume. scanBootVolumes(gBIOSDev, 0); bvChain = getBVChainForBIOSDev(gBIOSDev); setBootGlobals(bvChain); // Load boot.plist config file status = loadChameleonConfig(&bootInfo->chameleonConfig); if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->chameleonConfig) && quiet) { gBootMode |= kBootModeQuiet; } // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->chameleonConfig) && instantMenu) { firstRun = false; } // Loading preboot ramdisk if exists. loadPrebootRAMDisk(); // Disable rescan option by default gEnableCDROMRescan = false; // Enable it with Rescan=y in system config if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->chameleonConfig) && gEnableCDROMRescan) { gEnableCDROMRescan = true; } // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config. rescanPrompt = false; if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->chameleonConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) { gEnableCDROMRescan = promptForRescanOption(); } // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config. if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->chameleonConfig) && gScanSingleDrive) { gScanSingleDrive = true; } // Create a list of partitions on device(s). if (gScanSingleDrive) { scanBootVolumes(gBIOSDev, &bvCount); } else { scanDisks(gBIOSDev, &bvCount); } // Create a separated bvr chain using the specified filters. bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount); gBootVolume = selectBootVolume(bvChain); // Intialize module system init_module_system(); #if DEBUG printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags); printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags); getchar(); #endif useGUI = true; // Override useGUI default getBoolForKey(kGUIKey, &useGUI, &bootInfo->chameleonConfig); if (useGUI && initGUI()) { // initGUI() returned with an error, disabling GUI. useGUI = false; } setBootGlobals(bvChain); // Parse args, load and start kernel. while (1) { bool tryresume, tryresumedefault, forceresume; bool usecache = false;//true; const char *val; int len, trycache, ret = -1; long flags, cachetime, kerneltime, exttime, sleeptime, time; void *binary = (void *)kLoadAddr; // additional variable for testing alternate kernel image locations on boot helper partitions. char bootFileSpec[512]; // Initialize globals. sysConfigValid = false; gErrors = false; status = getBootOptions(firstRun); firstRun = false; if (status == -1) continue; status = processBootOptions(); // Status == 1 means to chainboot if ( status == 1 ) break; // Status == -1 means that the config file couldn't be loaded or that gBootVolume is NULL if ( status == -1 ) { // gBootVolume == NULL usually means the user hit escape. if (gBootVolume == NULL) { freeFilteredBVChain(bvChain); if (gEnableCDROMRescan) rescanBIOSDevice(gBIOSDev); bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount); setBootGlobals(bvChain); setupDeviceList(&bootInfo->themeConfig); } continue; } // Other status (e.g. 0) means that we should proceed with boot. // Turn off any GUI elements if ( bootArgs->Video.v_display == GRAPHICS_MODE ) { gui.devicelist.draw = false; gui.bootprompt.draw = false; gui.menu.draw = false; gui.infobox.draw = false; gui.logo.draw = false; drawBackground(); updateVRAM(); } // Find out which version mac os we're booting. getOSVersion(); if (platformCPUFeature(CPU_FEATURE_EM64T)) { archCpuType = CPU_TYPE_X86_64; } else { archCpuType = CPU_TYPE_I386; } if (getValueForKey(karch, &val, &len, &bootInfo->chameleonConfig)) { if (strncmp(val, "i386", 4) == 0) { archCpuType = CPU_TYPE_I386; } } if (getValueForKey(kKernelArchKey, &val, &len, &bootInfo->chameleonConfig)) { if (strncmp(val, "i386", 4) == 0) { archCpuType = CPU_TYPE_I386; } } // Notify modules that we are attempting to boot execute_hook("PreBoot", NULL, NULL, NULL, NULL); if (!getBoolForKey (kWake, &tryresume, &bootInfo->chameleonConfig)) { tryresume = true; tryresumedefault = true; } else { tryresumedefault = false; } if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->chameleonConfig)) { forceresume = false; } if (forceresume) { tryresume = true; tryresumedefault = false; } while (tryresume) { const char *tmp; BVRef bvr; if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->chameleonConfig)) val = "/private/var/vm/sleepimage"; // Do this first to be sure that root volume is mounted ret = GetFileInfo(0, val, &flags, &sleeptime); if ((bvr = getBootVolumeRef(val, &tmp)) == NULL) break; // Can't check if it was hibernation Wake=y is required if (bvr->modTime == 0 && tryresumedefault) break; if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) break; if (!forceresume && ((sleeptime+3)<bvr->modTime)) { #if DEBUG printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n", bvr->modTime-sleeptime); #endif break; } HibernateBoot((char *)val); break; } getBoolForKey(kUseKernelCache, &usecache, &bootInfo->chameleonConfig); if (usecache) { if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) { if (val[0] == '\\') { len--; val++; } strlcpy(gBootKernelCacheFile, val, len + 1); } else { //Lion if (checkOSVersion("10.7")) { sprintf(gBootKernelCacheFile, "%skernelcache", kDefaultCachePathSnow); } // Snow Leopard else if (checkOSVersion("10.6")) { sprintf(gBootKernelCacheFile, "kernelcache_%s", (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64"); int lnam = sizeof(gBootKernelCacheFile) + 9; //with adler32 char* name; long prev_time = 0; struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow); while(readdir(cacheDir, (const char**)&name, &flags, &time) >= 0) { if (((flags & kFileTypeMask) != kFileTypeDirectory) && time > prev_time && strstr(name, gBootKernelCacheFile) && (name[lnam] != '.')) { sprintf(gBootKernelCacheFile, "%s%s", kDefaultCachePathSnow, name); prev_time = time; } } } else { // Reset cache name. bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64); sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile); adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler)); sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePathLeo, adler32); } } } // Check for cache file. trycache = (usecache && ((gBootMode & kBootModeSafe) == 0) && !gOverrideKernel && (gBootFileType == kBlockDeviceType) && (gMKextName[0] == '\0') && (gBootKernelCacheFile[0] != '\0')); verbose("Loading Darwin %s\n", gMacOSVersion); if (trycache) do { ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime); if (ret != 0) kerneltime = 0; else if ((flags & kFileTypeMask) != kFileTypeFlat) { trycache = 0; break; } ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime); if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat) || (cachetime < kerneltime)) { trycache = 0; break; } ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime); if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory) && (cachetime < exttime)) { trycache = 0; break; } if (ret == 0 && kerneltime > exttime) { exttime = kerneltime; } if (ret == 0 && cachetime != (exttime + 1)) { trycache = 0; break; } } while (0); do { if (trycache) { bootFile = gBootKernelCacheFile; verbose("Loading kernel cache %s\n", bootFile); if (checkOSVersion("10.7")) { ret = LoadThinFatFile(bootFile, &binary); } else { ret = LoadFile(bootFile); binary = (void *)kLoadAddr; } if (ret >= 0) break; verbose("Kernel cache did not load %s\n ", bootFile); } if (checkOSVersion("10.7")) { bootFile = gBootKernelCacheFile; } else { sprintf(bootFile, "\%s", bootInfo->bootFile); } // Try to load kernel image from alternate locations on boot helper partitions. sprintf(bootFileSpec, "com.apple.boot.P%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { sprintf(bootFileSpec, "com.apple.boot.R%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { sprintf(bootFileSpec, "com.apple.boot.S%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { // No alternate location found, using the original kernel image path. strcpy(bootFileSpec, bootInfo->bootFile); } } } if (checkOSVersion("10.7")) { //Lion, dont load kernel if haz cache if (!trycache) { verbose("Loading kernel %s\n", bootFileSpec); ret = LoadThinFatFile(bootFileSpec, &binary); if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) { archCpuType = CPU_TYPE_I386; ret = LoadThinFatFile(bootFileSpec, &binary); } } else ret = 1; } else { //Snow Leopard or older verbose("Loading kernel %s\n", bootFileSpec); ret = LoadThinFatFile(bootFileSpec, &binary); if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) { archCpuType = CPU_TYPE_I386; ret = LoadThinFatFile(bootFileSpec, &binary); } } } while (0); clearActivityIndicator(); #if DEBUG printf("Pausing..."); sleep(8); #endif if (ret <= 0) { printf("Can't find %s\n", bootFile); sleep(1); if (gBootFileType == kNetworkDeviceType) { // Return control back to PXE. Don't unload PXE base code. gUnloadPXEOnExit = false; break; } } else { /* Won't return if successful. */ ret = ExecKernel(binary); } } // chainboot if (status == 1) { // if we are already in graphics-mode, if (getVideoMode() == GRAPHICS_MODE) { setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode. } } if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) { nbpUnloadBaseCode(); } }
//========================================================================== // The 'main' function for the booter. Called by boot0 when booting // from a block device, or by the network booter. // // arguments: // biosdev - Value passed from boot1/NBP to specify the device // that the booter was loaded from. // // If biosdev is kBIOSDevNetwork, then this function will return if // booting was unsuccessful. This allows the PXE firmware to try the // next boot device on its list. void common_boot(int biosdev) { int status; char *bootFile; unsigned long adler32; bool quiet; bool firstRun = true; bool instantMenu; bool rescanPrompt = false; unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot; unsigned int denyBVFlags = kBVFlagEFISystem; // Set reminder to unload the PXE base code. Neglect to unload // the base code will result in a hang or kernel panic. gUnloadPXEOnExit = true; // Record the device that the booter was loaded from. gBIOSDev = biosdev & kBIOSDevMask; // Initialize boot info structure. initKernBootStruct(); initBooterLog(); // Setup VGA text mode. // Not sure if it is safe to call setVideoMode() before the // config table has been loaded. Call video_mode() instead. #if DEBUG printf("before video_mode\n"); //Azi: this one is not printing... i remember it did.. check trunk. #endif video_mode( 2 ); // 80x25 mono text mode. #if DEBUG printf("after video_mode\n"); #endif // Scan and record the system's hardware information. scan_platform(); // First get info for boot volume. scanBootVolumes(gBIOSDev, 0); bvChain = getBVChainForBIOSDev(gBIOSDev); //Azi: initialising gBIOSBootVolume & gBootVolume (Startup volume) for the first time.. i think!? // also, kDefaultPartitionKey is checked here, on selectBootVolume. setBootGlobals(bvChain); msglog("setBootGlobals:\n Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags); msglog(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags); // Boot Volume is set as Root at this point so, pointing to Extra, /Extra or bt(0,0)/Extra // is exactly the same. Review bt(0,0)/bla bla paths...... (Reviewing...) //Azi: works as expected but... trying this because Kernel=mach_kernel doesn't work on a // override Boot.plist; this makes it impossible to override e.g. Kernel=bt(0,0)mach_kernel // on the main Boot.plist, when loading kernel from ramdisk btAliased. loadPrebootRAMDisk(); // Load boot.plist config file //Azi: on this first check, boot.plist acts as both "booter config file" // and bootargs/options "carrier".***** status = loadSystemConfig(&bootInfo->bootConfig); if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet) { gBootMode |= kBootModeQuiet; } // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu) { firstRun = false; } // Loading preboot ramdisk if exists. // loadPrebootRAMDisk(); //Azi: this needs to be done before load_all_modules() // because of btAlias... (Reviewing...) // Intialize module system if (init_module_system()) { load_all_modules(); } // Disable rescan option by default gEnableCDROMRescan = false; // If we're loading the booter from optical media... (Reviewing...) if (biosDevIsCDROM(gBIOSDev)) { // ... ask the user for Rescan option by setting "Rescan Prompt"=y in system config... if (getBoolForKey(kRescanPromptKey, &rescanPrompt, &bootInfo->bootConfig) && rescanPrompt) { gEnableCDROMRescan = promptForRescanOption(); } else // ... or enable it with Rescan=y in system config. if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan) { gEnableCDROMRescan = true; } } //Azi: Is this a cdrom only thing? (Reviewing...) // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config. if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive) { scanBootVolumes(gBIOSDev, &bvCount); } else { //Azi: scanDisks uses scanBootVolumes. scanDisks(gBIOSDev, &bvCount); } // Create a separated bvr chain using the specified filters. bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount); gBootVolume = selectBootVolume(bvChain); //#if DEBUG //printf msglog(":something...???\n Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags); msglog(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags); // getchar(); //#endif useGUI = true; // Override useGUI default getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig); // AutoResolution - Azi: default to false // http://forum.voodooprojects.org/index.php/topic,1227.0.html gAutoResolution = false; // Check if user enabled AutoResolution on Boot.plist... getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig); // Patch the Video Bios with the extracted resolution, before initGui. if (gAutoResolution == true) { initAutoRes(); } if (useGUI && initGUI()) { // initGUI() returned with an error, disabling GUI. useGUI = false; } setBootGlobals(bvChain); msglog("setBootGlobals:\n Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags); msglog(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags); // Parse args, load and start kernel. while (1) { const char *val; int len; int trycache; long flags, cachetime, kerneltime, exttime, sleeptime, time; int ret = -1; void *binary = (void *)kLoadAddr; bool tryresume; bool tryresumedefault; bool forceresume; bool ignoreKC = false; // additional variable for testing alternate kernel image locations on boot helper partitions. char bootFileSpec[512]; // Initialize globals. sysConfigValid = false; gErrors = false; status = getBootOptions(firstRun); firstRun = false; if (status == -1) continue; //Azi: test (gBootVolume == NULL) - so far Ok! // test with optical media again...? // Turn off any GUI elements, draw background and update VRAM. if ( bootArgs->Video.v_display == GRAPHICS_MODE ) { gui.devicelist.draw = false; gui.bootprompt.draw = false; gui.menu.draw = false; gui.infobox.draw = false; gui.logo.draw = false; drawBackground(); updateVRAM(); } status = processBootOptions(); //Azi: AutoResolution - closing Vbios here without restoring, causes an allocation error, // if the user tries to boot, after a e.g."Can't find bla_kernel" msg. // Doing it on execKernel() instead. // Status == 1 means to chainboot if ( status == 1 ) break; // Status == -1 means that gBootVolume is NULL. Config file is not mandatory anymore! if ( status == -1 ) { // gBootVolume == NULL usually means the user hit escape. (Reviewing...) if (gBootVolume == NULL) { freeFilteredBVChain(bvChain); if (gEnableCDROMRescan) rescanBIOSDevice(gBIOSDev); bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount); setBootGlobals(bvChain); setupDeviceList(&bootInfo->themeConfig); } continue; } // Other status (e.g. 0) means that we should proceed with boot. // If cpu handles 64 bit instructions... if (platformCPUFeature(CPU_FEATURE_EM64T)) { // use x86_64 kernel arch,... archCpuType = CPU_TYPE_X86_64; } else { // else use i386 kernel arch. archCpuType = CPU_TYPE_I386; } // If user override... if (getValueForKey(kArchKey, &val, &len, &bootInfo->bootConfig)) { // matches i386... if (strncmp(val, "i386", 4) == 0) { // use i386 kernel arch. archCpuType = CPU_TYPE_I386; } } if (!getBoolForKey (kWakeKey, &tryresume, &bootInfo->bootConfig)) { tryresume = true; tryresumedefault = true; } else { tryresumedefault = false; } if (!getBoolForKey (kForceWakeKey, &forceresume, &bootInfo->bootConfig)) { forceresume = false; } if (forceresume) { tryresume = true; tryresumedefault = false; } while (tryresume) { const char *tmp; BVRef bvr; if (!getValueForKey(kWakeKeyImageKey, &val, &len, &bootInfo->bootConfig)) val="/private/var/vm/sleepimage"; // Do this first to be sure that root volume is mounted ret = GetFileInfo(0, val, &flags, &sleeptime); if ((bvr = getBootVolumeRef(val, &tmp)) == NULL) break; // Can't check if it was hibernation Wake=y is required if (bvr->modTime == 0 && tryresumedefault) break; if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) break; if (!forceresume && ((sleeptime+3)<bvr->modTime)) { //Azi: no need for printf at this point - reminder printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override.\n",bvr->modTime-sleeptime); break; } HibernateBoot((char *)val); break; } //Azi:kernelcache stuff bool patchKernel = false; getBoolForKey(kKPatcherKey, &patchKernel, &bootInfo->bootConfig); //Azi: avoiding having to use -f to ignore kernel cache //Azi: ignore kernel cache but still use kext cache (E/E.mkext & S/L/E.mkext). - explain... getBoolForKey(kUseKCKey, &ignoreKC, &bootInfo->bootConfig); // equivalent to UseKernelCache if (ignoreKC) { verbose("KC: cache ignored by user.\n"); // make sure the damn thing get's zeroed, just in case... :)* bzero(gBootKernelCacheFile, sizeof(gBootKernelCacheFile)); } else if (patchKernel) // to be moved..? { verbose("KC: kernel patcher enabled, ignore cache.\n"); bzero(gBootKernelCacheFile, sizeof(gBootKernelCacheFile)); } else if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) { strlcpy(gBootKernelCacheFile, val, len + 1); verbose("KC: path set by user = %s\n", gBootKernelCacheFile); //Azi: bypass time check when user sets path ??? // cache is still ignored if time doesn't match... (e.g. booter on usb stick) } else { // Reset cache name. bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64); // kextcache_main.c: Construct entry from UUID of boot volume...(reminder) // assemble ?string? to generate adler from... // sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile); - OLD const char *ProductName = getStringForKey("SMproductname", &bootInfo->smbiosConfig); sprintf(gCacheNameAdler, ProductName); // well, at least the smbios.plist can be loaded this early... // to set/get "ProductName" this early, booter needs complete rewrite!! // see DHP's Revolution booter rework example! // verbose("KC: gCacheNameAdler 1 = %s\n", gCacheNameAdler); //Azi: check the validity of this, e.g. on Helper Partitions sprintf(gCacheNameAdler + 64, "%s", "\\System\\Library\\CoreServices\\boot.efi"); // verbose("KC: gCacheNameAdler 2 = %s\n", gCacheNameAdler + 64); sprintf(gCacheNameAdler + (64 + 38), "%s", bootInfo->bootFile); // verbose("KC: gCacheNameAdler 3 = %s\n", gCacheNameAdler + (64 + 38)); // generate adler adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler)); // verbose("KC: Adler32 = %08X\n", adler32); //Azi: no check for OS version here ?? - yes there is :) // append arch and/or adler (checksum) to kc path... if (gMacOSVersion[3] <= '5') { sprintf(gBootKernelCacheFile, "%s.%08lX", kCachePathTigerLeopard, adler32); // verbose("KC: adler added to path = %s\n", gBootKernelCacheFile); } else { sprintf(gBootKernelCacheFile, "%s_%s.%08X", kCachePathSnowLion, (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64", adler32); // verbose("KC: arch & adler added to path = %s\n", gBootKernelCacheFile); } } // Check for cache file. //Azi: trycache is done if... trycache = ( ( (gBootMode & kBootModeSafe) == 0) //... we're not booting in safe mode (-x arg), && !gOverrideKernel // we're not overriding default kernel "name", && (gBootFileType == kBlockDeviceType) // we're booting from local storage device, && (gMKextName[0] == '\0') // "MKext Cache" key IS NOT in use, and && (gBootKernelCacheFile[0] != '\0') ); // gBootKernelCacheFile is populated. // we could add the use of "kernelpatcher" to this bunch..?? // verbose("Loading Darwin %s\n", gMacOSVersion); //Azi: move?? to getOSVersion? :) if (trycache) do { verbose("KC: checking kernel cache (system prelinked kernel)...\n"); // if we haven't found the kernel yet, don't use the cache ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime); if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) { verbose("KC: no kernel found (shouldn't happen?!?)\n"); trycache = 0; // ignore kernel cache... break; } verbose("KC: kerneltime = %d\n", kerneltime); ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime); if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat) || (cachetime < kerneltime)) { if (cachetime <= 100) // confirm: 100 = inexistent path, -xxxxxxxxx = wrong name // not confirming... i also get -xxxxxxxxx with inexisting prelinked kernel verbose("KC: cachetime = %d, kernel cache path/adler is incorrect, ignoring it. ??? \n", cachetime); else verbose("KC: cachetime = %d, kernel cache is older than the kernel, ignoring it.\n", cachetime); trycache = 0; break; } verbose("KC: cachetime = %d\n", cachetime); ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime); if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory) && (cachetime < exttime)) { verbose("KC: exttime = %d, kernel cache is older than S/L/E, ignoring it.\n", exttime); trycache = 0; break; } verbose("KC: exttime = %d\n", exttime); if (kerneltime > exttime) // if S/L/E is older than the kernel... { verbose("KC: S/L/E is older than the kernel, matching exttime with kerneltime...\n"); exttime = kerneltime; } verbose("KC: exttime +1 = %d\n", exttime + 1); if (cachetime != (exttime + 1)) { verbose("KC: kernel cache time is diff from S/L/E time, ignoring it.\n"); trycache = 0; break; } verbose("KC: kernel cache found and up to date, will be used.\n"); } while (0); do { // Load kernel cache if not ignored. if (trycache) { bootFile = gBootKernelCacheFile; verbose("Loading kernel cache %s\n", bootFile); ret = LoadFile(bootFile); binary = (void *)kLoadAddr; if (ret >= 0) { break; } } bootFile = bootInfo->bootFile; // Try to load kernel image from alternate locations on boot helper partitions. sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { // No alternate location found, using the original kernel image path. strcpy(bootFileSpec, bootFile); } } } verbose("Loading kernel %s\n", bootFileSpec); ret = LoadThinFatFile(bootFileSpec, &binary); if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) { archCpuType = CPU_TYPE_I386; ret = LoadThinFatFile(bootFileSpec, &binary); } } while (0); clearActivityIndicator(); /*#if DEBUG printf("Pausing..."); sleep(8); #endif Azi: annoying stuff :P */ if (ret <= 0) { printf("Can't find %s\n", bootFile); sleep(1); if (gBootFileType == kNetworkDeviceType) { // Return control back to PXE. Don't unload PXE base code. gUnloadPXEOnExit = false; break; } } else { // Won't return if successful. ret = ExecKernel(binary); } } // while (1) // chainboot if (status==1) { if (getVideoMode() == GRAPHICS_MODE) { // if we are already in graphics-mode, setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode } } if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) { nbpUnloadBaseCode(); } }
int getBootOptions(bool firstRun) { int i; int key; int nextRow; int timeout; // int bvCount; BVRef bvr; BVRef menuBVR; bool showPrompt, newShowPrompt, isCDROM; // Initialize default menu selection entry. gBootVolume = menuBVR = selectBootVolume(bvChain); if (biosDevIsCDROM(gBIOSDev)) { isCDROM = true; } else { isCDROM = false; } // ensure we're in graphics mode if gui is setup if (gui.initialised && bootArgs->Video.v_display == VGA_TEXT_MODE) { setVideoMode(GRAPHICS_MODE, 0); } // Clear command line boot arguments clearBootArgs(); // Allow user to override default timeout. if (multiboot_timeout_set) { timeout = multiboot_timeout; } else if (!getIntForKey(kTimeoutKey, &timeout, &bootInfo->bootConfig)) { /* If there is no timeout key in the file use the default timeout which is different for CDs vs. hard disks. However, if not booting a CD and no config file could be loaded set the timeout to zero which causes the menu to display immediately. This way, if no partitions can be found, that is the disk is unpartitioned or simply cannot be read) then an empty menu is displayed. If some partitions are found, for example a Windows partition, then these will be displayed in the menu as foreign partitions. */ if (isCDROM) { timeout = kCDBootTimeout; } else { timeout = sysConfigValid ? kBootTimeout : 0; } } if (timeout < 0) { gBootMode |= kBootModeQuiet; } // If the user is holding down a modifier key, enter safe mode. if ((readKeyboardShiftFlags() & 0x0F) != 0) { gBootMode |= kBootModeSafe; } // Checking user pressed keys bool f8press = false, spress = false, vpress = false; while (readKeyboardStatus()) { key = bgetc (); if (key == 0x4200) f8press = true; if ((key & 0xff) == 's' || (key & 0xff) == 'S') spress = true; if ((key & 0xff) == 'v' || (key & 0xff) == 'V') vpress = true; } // If user typed F8, abort quiet mode, and display the menu. if (f8press) { gBootMode &= ~kBootModeQuiet; timeout = 0; } // If user typed 'v' or 'V', boot in verbose mode. if ((gBootMode & kBootModeQuiet) && firstRun && vpress) { addBootArg(kVerboseModeFlag); } // If user typed 's' or 'S', boot in single user mode. if ((gBootMode & kBootModeQuiet) && firstRun && spress) { addBootArg(kSingleUserModeFlag); } if (bootArgs->Video.v_display == VGA_TEXT_MODE) { setCursorPosition(0, 0, 0); clearScreenRows(0, kScreenLastRow); if (!(gBootMode & kBootModeQuiet)) { // Display banner and show hardware info. verbose(bootBanner, (bootInfo->convmem + bootInfo->extmem) / 1024); verbose(getVBEInfoString()); } changeCursor(0, kMenuTopRow, kCursorTypeUnderline, 0); verbose("Scanning device %x...", gBIOSDev); } // When booting from CD, default to hard drive boot when possible. if (isCDROM && firstRun) { const char *val; char *prompt = NULL; char *name = NULL; int cnt; int optionKey; if (getValueForKey(kCDROMPromptKey, &val, &cnt, &bootInfo->bootConfig)) { prompt = malloc(cnt + 1); strncat(prompt, val, cnt); } else { name = malloc(80); getBootVolumeDescription(gBootVolume, name, 79, false); prompt = malloc(256); sprintf(prompt, "Press any key to start up from %s, or press F8 to enter startup options.", name); free(name); } if (getIntForKey( kCDROMOptionKey, &optionKey, &bootInfo->bootConfig )) { // The key specified is a special key. } else { // Default to F8. optionKey = 0x4200; } // If the timeout is zero then it must have been set above due to the // early catch of F8 which means the user wants to set boot options // which we ought to interpret as meaning he wants to boot the CD. if (timeout != 0) { key = countdown(prompt, kMenuTopRow, timeout); } else { key = optionKey; } if (prompt != NULL) { free(prompt); } clearScreenRows( kMenuTopRow, kMenuTopRow + 2 ); // Hit the option key ? if (key == optionKey) { gBootMode &= ~kBootModeQuiet; timeout = 0; } else { key = key & 0xFF; // Try booting hard disk if user pressed 'h' if (biosDevIsCDROM(gBIOSDev) && key == 'h') { BVRef bvr; // Look at partitions hosting OS X other than the CD-ROM for (bvr = bvChain; bvr; bvr=bvr->next) { if ((bvr->flags & kBVFlagSystemVolume) && bvr->biosdev != gBIOSDev) { gBootVolume = bvr; } } } goto done; } } if (gBootMode & kBootModeQuiet) { // No input allowed from user. goto done; } if (firstRun && timeout > 0 && countdown("Press any key to enter startup options.", kMenuTopRow, timeout) == 0) { // If the user is holding down a modifier key, // enter safe mode. if ((readKeyboardShiftFlags() & 0x0F) != 0) { gBootMode |= kBootModeSafe; } goto done; } if (gDeviceCount) { // Allocate memory for an array of menu items. menuItems = malloc(sizeof(MenuItem) * gDeviceCount); if (menuItems == NULL) { goto done; } // Associate a menu item for each BVRef. for (bvr=bvChain, i=gDeviceCount-1, selectIndex=0; bvr; bvr=bvr->next) { if (bvr->visible) { getBootVolumeDescription(bvr, menuItems[i].name, sizeof(menuItems[i].name) - 1, true); menuItems[i].param = (void *) bvr; if (bvr == menuBVR) { selectIndex = i; } i--; } } } if (bootArgs->Video.v_display == GRAPHICS_MODE) { // redraw the background buffer gui.logo.draw = true; drawBackground(); gui.devicelist.draw = true; gui.redraw = true; if (!(gBootMode & kBootModeQuiet)) { bool showBootBanner = true; // Check if "Boot Banner"=N switch is present in config file. getBoolForKey(kBootBannerKey, &showBootBanner, &bootInfo->bootConfig); if (showBootBanner) { // Display banner and show hardware info. gprintf(&gui.screen, bootBanner + 1, (bootInfo->convmem + bootInfo->extmem) / 1024); } // redraw background memcpy(gui.backbuffer->pixels, gui.screen.pixmap->pixels, gui.backbuffer->width * gui.backbuffer->height * 4); } } else { // Clear screen and hide the blinking cursor. clearScreenRows(kMenuTopRow, kMenuTopRow + 2); changeCursor(0, kMenuTopRow, kCursorTypeHidden, 0); } nextRow = kMenuTopRow; showPrompt = true; if (gDeviceCount) { if( bootArgs->Video.v_display == VGA_TEXT_MODE ) { printf("Use \30\31 keys to select the startup volume."); } showMenu( menuItems, gDeviceCount, selectIndex, kMenuTopRow + 2, kMenuMaxItems ); nextRow += min( gDeviceCount, kMenuMaxItems ) + 3; } // Show the boot prompt. showPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot); showBootPrompt( nextRow, showPrompt ); do { if (bootArgs->Video.v_display == GRAPHICS_MODE) { // redraw background memcpy( gui.backbuffer->pixels, gui.screen.pixmap->pixels, gui.backbuffer->width * gui.backbuffer->height * 4 ); // reset cursor co-ords gui.debug.cursor = pos( gui.screen.width - 160 , 10 ); } key = getc(); updateMenu( key, (void **) &menuBVR ); newShowPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot); if (newShowPrompt != showPrompt) { showPrompt = newShowPrompt; showBootPrompt( nextRow, showPrompt ); } if (showPrompt) { updateBootArgs(key); } switch (key) { case kReturnKey: if (gui.menu.draw) { key=0; break; } if (*gBootArgs == '?') { char * argPtr = gBootArgs; // Skip the leading "?" character. argPtr++; getNextArg(&argPtr, booterCommand); getNextArg(&argPtr, booterParam); /* * TODO: this needs to be refactored. */ if (strcmp( booterCommand, "video" ) == 0) { if (bootArgs->Video.v_display == GRAPHICS_MODE) { showInfoBox(getVBEInfoString(), getVBEModeInfoString()); } else { printVBEModeInfo(); } } else if ( strcmp( booterCommand, "memory" ) == 0) { if (bootArgs->Video.v_display == GRAPHICS_MODE ) { showInfoBox("Memory Map", getMemoryInfoString()); } else { printMemoryInfo(); } } else if (strcmp(booterCommand, "lspci") == 0) { lspci(); } else if (strcmp(booterCommand, "more") == 0) { showTextFile(booterParam); } else if (strcmp(booterCommand, "rd") == 0) { processRAMDiskCommand(&argPtr, booterParam); } else if (strcmp(booterCommand, "norescan") == 0) { if (gEnableCDROMRescan) { gEnableCDROMRescan = false; break; } } else { showHelp(); } key = 0; showBootPrompt(nextRow, showPrompt); break; } gBootVolume = menuBVR; setRootVolume(menuBVR); gBIOSDev = menuBVR->biosdev; break; case kEscapeKey: clearBootArgs(); break; case kF5Key: // New behavior: // Clear gBootVolume to restart the loop // if the user enabled rescanning the optical drive. // Otherwise boot the default boot volume. if (gEnableCDROMRescan) { gBootVolume = NULL;//Slice -???? clearBootArgs(); } break; case kF10Key: gScanSingleDrive = false; scanDisks(gBIOSDev, &bvCount); gBootVolume = NULL; clearBootArgs(); break; case kTabKey: // New behavior: // Switch between text & graphic interfaces // Only Permitted if started in graphics interface if (useGUI) { if (bootArgs->Video.v_display == GRAPHICS_MODE) { setVideoMode(VGA_TEXT_MODE, 0); setCursorPosition(0, 0, 0); clearScreenRows(0, kScreenLastRow); // Display banner and show hardware info. printf(bootBanner, (bootInfo->convmem + bootInfo->extmem) / 1024); printf(getVBEInfoString()); clearScreenRows(kMenuTopRow, kMenuTopRow + 2); changeCursor(0, kMenuTopRow, kCursorTypeHidden, 0); nextRow = kMenuTopRow; showPrompt = true; if (gDeviceCount) { printf("Use \30\31 keys to select the startup volume."); showMenu(menuItems, gDeviceCount, selectIndex, kMenuTopRow + 2, kMenuMaxItems); nextRow += min(gDeviceCount, kMenuMaxItems) + 3; } showPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot); showBootPrompt(nextRow, showPrompt); //changeCursor( 0, kMenuTopRow, kCursorTypeUnderline, 0 ); } else { gui.redraw = true; setVideoMode(GRAPHICS_MODE, 0); updateVRAM(); } } key = 0; break; default: key = 0; break; } } while (0 == key); done: if (bootArgs->Video.v_display == VGA_TEXT_MODE) { clearScreenRows(kMenuTopRow, kScreenLastRow); changeCursor(0, kMenuTopRow, kCursorTypeUnderline, 0); } shouldboot = false; gui.menu.draw = false; if (menuItems) { free(menuItems); menuItems = NULL; } return 0; }
void QgsComposerLabel::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) { Q_UNUSED( itemStyle ); Q_UNUSED( pWidget ); if ( !painter ) { return; } drawBackground( painter ); painter->save(); double penWidth = pen().widthF(); QRectF painterRect( penWidth + mMargin, penWidth + mMargin, mTextBoxWidth - 2 * penWidth - 2 * mMargin, mTextBoxHeight - 2 * penWidth - 2 * mMargin ); painter->translate( rect().width() / 2.0, rect().height() / 2.0 ); painter->rotate( mRotation ); painter->translate( -mTextBoxWidth / 2.0, -mTextBoxHeight / 2.0 ); if ( mHtmlState ) { painter->scale( 1.0 / mHtmlUnitsToMM / 10.0, 1.0 / mHtmlUnitsToMM / 10.0 ); QWebPage* webPage = new QWebPage(); //Setup event loop and timeout for rendering html QEventLoop loop; QTimer timeoutTimer; timeoutTimer.setSingleShot( true ); //This makes the background transparent. Found on http://blog.qt.digia.com/blog/2009/06/30/transparent-qwebview-or-qwebpage/ QPalette palette = webPage->palette(); palette.setBrush( QPalette::Base, Qt::transparent ); webPage->setPalette( palette ); //webPage->setAttribute(Qt::WA_OpaquePaintEvent, false); //this does not compile, why ? webPage->setViewportSize( QSize( painterRect.width() * mHtmlUnitsToMM * 10.0, painterRect.height() * mHtmlUnitsToMM * 10.0 ) ); webPage->mainFrame()->setZoomFactor( 10.0 ); webPage->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff ); webPage->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff ); // QGIS segfaults when rendering web page while in composer if html // contains images. So if we are not printing the composition, then // disable image loading if ( mComposition->plotStyle() != QgsComposition::Print && mComposition->plotStyle() != QgsComposition::Postscript ) { webPage->settings()->setAttribute( QWebSettings::AutoLoadImages, false ); } //Connect timeout and webpage loadFinished signals to loop connect( &timeoutTimer, SIGNAL( timeout() ), &loop, SLOT( quit() ) ); connect( webPage, SIGNAL( loadFinished( bool ) ), &loop, SLOT( quit() ) ); //mHtmlLoaded tracks whether the QWebPage has completed loading //its html contents, set it initially to false. The loadingHtmlFinished slot will //set this to true after html is loaded. mHtmlLoaded = false; connect( webPage, SIGNAL( loadFinished( bool ) ), SLOT( loadingHtmlFinished( bool ) ) ); webPage->mainFrame()->setHtml( displayText() ); //For very basic html labels with no external assets, the html load will already be //complete before we even get a chance to start the QEventLoop. Make sure we check //this before starting the loop if ( !mHtmlLoaded ) { // Start a 20 second timeout in case html loading will never complete timeoutTimer.start( 20000 ); // Pause until html is loaded loop.exec(); } webPage->mainFrame()->render( painter );//DELETE WEBPAGE ? } else {
/*! Renders the delegate using the given \a painter and style \a option for the item specified by \a index. When reimplementing this function in a subclass, you should update the area held by the option's \l{QStyleOption::rect}{rect} variable, using the option's \l{QStyleOption::state}{state} variable to determine the state of the item to be displayed, and adjust the way it is painted accordingly. For example, a selected item may need to be displayed differently to unselected items, as shown in the following code: \snippet itemviews/pixelator/pixeldelegate.cpp 2 \dots After painting, you should ensure that the painter is returned to its the state it was supplied in when this function was called. For example, it may be useful to call QPainter::save() before painting and QPainter::restore() afterwards. \sa QStyle::State */ void QItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_D(const QItemDelegate); Q_ASSERT(index.isValid()); QStyleOptionViewItem opt = setOptions(index, option); // prepare painter->save(); if (d->clipPainting) painter->setClipRect(opt.rect); // get the data and the rectangles QVariant value; QPixmap pixmap; QRect decorationRect; value = index.data(Qt::DecorationRole); if (value.isValid()) { // ### we need the pixmap to call the virtual function pixmap = decoration(opt, value); if (value.type() == QVariant::Icon) { d->tmp.icon = qvariant_cast<QIcon>(value); d->tmp.mode = d->iconMode(option.state); d->tmp.state = d->iconState(option.state); const QSize size = d->tmp.icon.actualSize(option.decorationSize, d->tmp.mode, d->tmp.state); decorationRect = QRect(QPoint(0, 0), size); } else { d->tmp.icon = QIcon(); decorationRect = QRect(QPoint(0, 0), pixmap.size()); } } else { d->tmp.icon = QIcon(); decorationRect = QRect(); } QString text; QRect displayRect; value = index.data(Qt::DisplayRole); if (value.isValid() && !value.isNull()) { text = QItemDelegatePrivate::valueToText(value, opt); displayRect = textRectangle(painter, d->textLayoutBounds(opt), opt.font, text); } QRect checkRect; Qt::CheckState checkState = Qt::Unchecked; value = index.data(Qt::CheckStateRole); if (value.isValid()) { checkState = static_cast<Qt::CheckState>(value.toInt()); checkRect = doCheck(opt, opt.rect, value); } // do the layout doLayout(opt, &checkRect, &decorationRect, &displayRect, false); // draw the item drawBackground(painter, opt, index); drawCheck(painter, opt, checkRect, checkState); drawDecoration(painter, opt, decorationRect, pixmap); drawDisplay(painter, opt, displayRect, text); drawFocus(painter, opt, displayRect); // done painter->restore(); }
void drawEverything() { drawBackground(BACKGROUND_COLOR); drawBall((size_t)(g_ballPosX), (size_t)(g_ballPosY), g_ballRadius, BALL_COLOR); drawRacket(g_player1PositionX, (size_t)(g_player1PosY), g_playerWidth, g_playerHeight, PLAYER1_COLOR); drawRacket(g_player2PositionX, (size_t)(g_player2PosY), g_playerWidth, g_playerHeight, PLAYER2_COLOR); }
void FractalMe(double time){ GLint loc; int frame = 0, bigframe = 30, bigframe2 = 30; float x, y, nextx, nexty; float particlerot = 0.0, particlexzoom = 2.94, particleyzoom = 2.95, particlexoffset = 1.11, particleyoffset = 1.77; float bigoffsetx = 1.3, bigoffsety = 1.7; float bgoffsety = 0.0; int i,j; if(time > 0.0 && time < 2.31){ bigframe = (int)(time / OUTLINE_FPS) % 30; bigframe2 = bigframe; frame = 0; } if(time > 2.31 && time < 14.9){ frame = (int)((time - 2.31) / OUTLINE_FPS) % fractalme.framenum; } if(time > 14.8){ frame = fractalme.framenum-1; particlerot = (time-14.8) / 2.0; particlexzoom += (time-14.8); particleyzoom += (time-14.8); particlexoffset += (time-14.8)/2.4; particleyoffset += (time-14.8)/2.0; } if(time > 17.0 && time < 27.69){ bigframe = (int)((time - 14.69) / OUTLINE_FPS) % fractalme.framenum; } if(time > 27.69){ bigoffsety += (time - 27.69); bgoffsety -= (time - 27.69); } glUseProgram(fractalme.shader); loc = glGetUniformLocation(fractalme.shader, "size"); glUniform1f(loc, 3.0); loc = glGetUniformLocation(fractalme.shader, "offset"); glUniform2f(loc, bigoffsetx, bigoffsety); loc = glGetUniformLocation(fractalme.shader, "angle"); glUniform1f(loc, M_PI); drawTriangulatedOutline(fractalme, bigframe); for(i = 0; i < fractalme.frames[bigframe2].contournum; i++){ for(j = 0; j < fractalme.frames[bigframe2].contours[i].coordnum; j += 2){ x = fractalme.frames[bigframe2].contours[i].coord[j] * particlexzoom - particlexoffset; y = particleyoffset - fractalme.frames[bigframe2].contours[i].coord[j+1] * particleyzoom; if(j+3 < fractalme.frames[bigframe2].contours[i].coordnum){ nextx = fractalme.frames[bigframe2].contours[i].coord[j+2] * particlexzoom - particlexoffset; nexty = particleyoffset - fractalme.frames[bigframe2].contours[i].coord[j+3] * particleyzoom; } else{ nextx = fractalme.frames[bigframe2].contours[i].coord[0] * particlexzoom - particlexoffset; nexty = particleyoffset - fractalme.frames[bigframe2].contours[i].coord[1] * particleyzoom; } loc = glGetUniformLocation(fractalme.shader, "offset"); glUniform2f(loc, x, y); loc = glGetUniformLocation(fractalme.shader, "size"); glUniform1f(loc, 0.1); loc = glGetUniformLocation(fractalme.shader, "angle"); glUniform1f(loc, atan2((nexty - y), (nextx - x)) + particlerot); loc = glGetUniformLocation(fractalme.shader, "center"); glUniform2f(loc, 0.0, 0.1); drawTriangulatedOutline(fractalme, frame); } } /* Draw background */ glUseProgram(background_shader); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, greentex); loc = glGetUniformLocation(background_shader, "image"); glUniform1i(loc, 0); loc = glGetUniformLocation(background_shader, "wtime"); glUniform1f(loc, time); loc = glGetUniformLocation(background_shader, "distfactor"); glUniform1f(loc, 0.0); loc = glGetUniformLocation(background_shader, "voffset"); glUniform2f(loc, 0.0, bgoffsety); drawBackground(); }
void Gource::draw(float t, float dt) { display.mode2D(); drawBackground(dt); if(draw_loading) { loadingScreen(); draw_loading = false; return; } Frustum frustum(camera); trace_time = SDL_GetTicks(); mousetrace(frustum,dt); trace_time = SDL_GetTicks() - trace_time; glMatrixMode(GL_PROJECTION); glLoadIdentity(); camera.focus(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //draw tree drawTree(frustum, dt); glColor4f(1.0, 1.0, 0.0, 1.0); for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { trace_debug ? it->second->drawSimple(dt) : it->second->draw(dt); } glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); //draw bloom drawBloom(frustum, dt); root->drawNames(font,frustum); if(!(gGourceSettings.hide_usernames || gGourceSettings.hide_users)) { for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { it->second->drawName(); } } //draw selected item names again so they are over the top if(selectedUser !=0) selectedUser->drawName(); if(selectedFile !=0) { vec2f dirpos = selectedFile->getDir()->getPos(); glPushMatrix(); glTranslatef(dirpos.x, dirpos.y, 0.0); selectedFile->drawName(); glPopMatrix(); } if(debug) { glDisable(GL_TEXTURE_2D); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); track_users ? user_bounds.draw() : dir_bounds.draw(); } if(gGourceQuadTreeDebug) { glDisable(GL_TEXTURE_2D); glColor4f(0.0f, 1.0f, 0.0f, 1.0f); glLineWidth(1.0); dirNodeTree->outline(); glColor4f(0.0f, 1.0f, 1.0f, 1.0f); userTree->outline(); } glColor4f(1.0f, 1.0f, 1.0f, 1.0f); display.mode2D(); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); vec3f campos = camera.getPos(); if(logotex!=0) { glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glColor4f(1.0, 1.0, 1.0, 1.0); glBindTexture(GL_TEXTURE_2D, logotex->textureid); vec2f logopos = vec2f(display.width, display.height) - vec2f(logotex->w, logotex->h) - gGourceSettings.logo_offset; glPushMatrix(); glTranslatef(logopos.x, logopos.y, 0.0); glBegin(GL_QUADS); glTexCoord2f(0.0f,0.0f); glVertex2i(0, 0); glTexCoord2f(1.0f,0.0f); glVertex2i(logotex->w, 0); glTexCoord2f(1.0f,1.0f); glVertex2i(logotex->w, logotex->h); glTexCoord2f(0.0f,1.0f); glVertex2i(0, logotex->h); glEnd(); glPopMatrix(); } if(splash>0.0f) { int logowidth = fontlarge.getWidth("Gource"); int logoheight = 100; int cwidth = font.getWidth("Software Version Control Visualization"); int awidth = font.getWidth("(C) 2009 Andrew Caudwell"); vec2f corner(display.width/2 - logowidth/2 - 30.0f, display.height/2 - 40); glDisable(GL_TEXTURE_2D); glColor4f(0.0f, 0.5f, 1.0f, splash * 0.015f); glBegin(GL_QUADS); glVertex2f(0.0f, corner.y); glVertex2f(0.0f, corner.y + logoheight); glVertex2f(display.width, corner.y + logoheight); glVertex2f(display.width, corner.y); glEnd(); glEnable(GL_TEXTURE_2D); glColor4f(1.0,1.0,1.0,1.0); fontlarge.draw(display.width/2 - logowidth/2,display.height/2 - 30, "Gource"); font.draw(display.width/2 - cwidth/2,display.height/2 + 10, "Software Version Control Visualization"); font.draw(display.width/2 - awidth/2,display.height/2 + 30, "(C) 2009 Andrew Caudwell"); } // text using the specified font goes here glColor4f(gGourceSettings.font_colour.x, gGourceSettings.font_colour.y, gGourceSettings.font_colour.z, 1.0f); if(!gGourceSettings.hide_date) { fontmedium.draw(display.width/2 - date_x_offset, 20, displaydate); } if(gGourceSettings.title.size()>0) { fontmedium.alignTop(false); fontmedium.draw(10, display.height - 10, gGourceSettings.title); fontmedium.alignTop(true); } if(message_timer>0.0f) { fontmedium.draw(1, 3, message); } // end text glColor4f(1.0f, 1.0f, 1.0f, 1.0f); if(debug) { font.print(1,20, "FPS: %.2f", fps); font.print(1,40,"Days Per Second: %.2f", gGourceSettings.days_per_second); font.print(1,60,"Time Scale: %.2f", time_scale); font.print(1,80,"Users: %d", users.size()); font.print(1,100,"Files: %d", files.size()); font.print(1,120,"Dirs: %d", gGourceDirMap.size()); font.print(1,140,"Log Position: %.4f", commitlog->getPercent()); font.print(1,160,"Camera: (%.2f, %.2f, %.2f)", campos.x, campos.y, campos.z); font.print(1,180,"Gravity: %.2f", gGourceForceGravity); font.print(1,200,"Update Tree: %u ms", update_dir_tree_time); font.print(1,220,"Draw Tree: %u ms", draw_tree_time); font.print(1,240,"Mouse Trace: %u ms", trace_time); font.print(1,260,"Logic Time: %u ms", logic_time); font.print(1,280,"Draw Time: %u ms", SDL_GetTicks() - draw_time); font.print(1,300,"File Inner Loops: %d", gGourceFileInnerLoops); font.print(1,320,"User Inner Loops: %d", gGourceUserInnerLoops); font.print(1,340,"Dir Inner Loops: %d (QTree items = %d, nodes = %d)", gGourceDirNodeInnerLoops, dirNodeTree->item_count, dirNodeTree->node_count); if(selectedUser != 0) { } if(selectedFile != 0) { font.print(1,360,"%s: %d files (%d visible)", selectedFile->getDir()->getPath().c_str(), selectedFile->getDir()->fileCount(), selectedFile->getDir()->visibleFileCount()); } } glDisable(GL_TEXTURE_2D); if(canSeek()) slider.draw(dt); mousemoved=false; mouseclicked=false; }
void Shape::onDraw(SkCanvas & canvas, const Rect & inval, float opacity) { if (opacity == 0) return; drawBackground(canvas, opacity); }
void Greetings(double time){ static Outline *outline = &run2; GLfloat avg[2] = {0.0, 0.0}; static int frame = 0, loopnum = 0; static double prev_time = 0.0; GLuint loc; int i; if(time - prev_time > OUTLINE_FPS){ frame++; prev_time = time; if(frame >= outline->framenum){ frame = 0; loopnum++; } } /* Choose acrobatic movements */ switch(loopnum){ case 8: outline = &tiger; break; case 16: outline = &katf; break; case 24: outline = &hop; break; case 32: outline = &tbill; break; case 40: outline = &catwheel; break; case 45: outline = &flip; break; default: outline = &run2; }; averageCoords(*outline, frame, avg); /* Draw running man */ glUseProgram(outline->shader); loc = glGetUniformLocation(outline->shader, "avg"); glUniform2f(loc, avg[0], avg[1]); loc = glGetUniformLocation(outline->shader, "offset"); glUniform2f(loc, 0.0, -1.5); drawTriangulatedOutline(*outline, frame); glUseProgram(scroll_shader); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, bgalphatex); loc = glGetUniformLocation(scroll_shader, "image"); glUniform1i(loc, 0); loc = glGetUniformLocation(scroll_shader, "wtime"); glUniform1f(loc, time); loc = glGetUniformLocation(scroll_shader, "distfactor"); glUniform1f(loc, 1.0); loc = glGetUniformLocation(background_shader, "voffset"); glUniform2f(loc, 0.0, 0.0); drawBackground(); for(i = 0; i < 12; i++){ drawGreetings(gr_shader, greetingstex[i], 52.0 / 12.0 * (float)(i) , -0.7, time); } }
void SDLFontGL::drawTextGL(TextGraphicsInfo_t & graphicsInfo, int nX, int nY, const char * text) { if (!GlyphCache) createTexture(); int fnt = graphicsInfo.font; int fg = graphicsInfo.fg; int bg = graphicsInfo.bg; int blink = graphicsInfo.blink; assert(fnt >= 0 && fnt < nFonts); assert(fg >= 0 && fg < nCols); assert(bg >= 0 && bg < nCols); assert(fnts && cols && GlyphCache); unsigned len = strlen(text); // Ensure we have the needed font/slots: ensureCacheLine(fnt, graphicsInfo.slot1); ensureCacheLine(fnt, graphicsInfo.slot2); const int stride = 12; // GL_TRIANGLE_STRIP 2*6 drawBackground(bg, nX, nY, len); if (blink) return; GLfloat *tex = &texValues[stride*numChars]; GLfloat *vtx = &vtxValues[stride*numChars]; GLfloat *clrs = &colorValues[2*stride*numChars]; numChars += len; float x_scale = ((float)nWidth) / (float)texW; float y_scale = ((float)nHeight) / (float)texH; GLfloat texCopy[] = { 0.0, 0.0, 0.0, y_scale, x_scale, 0.0, 0.0, y_scale, x_scale, 0.0, x_scale, y_scale }; GLfloat vtxCopy[] = { nX, nY, nX, nY + nHeight, nX + nWidth, nY, nX, nY + nHeight, nX + nWidth, nY, nX + nWidth, nY + nHeight }; SDL_Color fgc = cols[fg]; GLfloat colorCopy[] = { ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f, ((float)fgc.r)/255.f, ((float)fgc.g)/255.f, ((float)fgc.b)/255.f, 1.f }; for (unsigned i = 0; i < len; ++i) { // Populate texture coordinates memcpy(&tex[i*stride],texCopy,sizeof(texCopy)); char c = text[i]; int x,y; getTextureCoordinates(graphicsInfo, c, x, y); float x_offset = ((float)x) / texW; float y_offset = ((float)y) / texH; for(unsigned j = 0; j < stride; j += 2) { tex[i*stride+j] += x_offset; tex[i*stride+j+1] += y_offset; } // Populate vertex coordinates memcpy(&vtx[i*stride],vtxCopy,sizeof(vtxCopy)); for(unsigned j = 0; j < stride; j += 2) { vtxCopy[j] += nWidth; } // Populate color coodinates memcpy(&clrs[i*2*stride], colorCopy, sizeof(colorCopy)); } }
void Speciesview::draw() { if (active) { unsigned int highestCount = 0; unsigned int highestAD = 0; unsigned int highestNeurons = 0; unsigned int highestSynapses = 0; unsigned int highestBodyparts = 0; // initialize sort indices // at the same time find the highest Counts for all columns vector<int> indices ( genotypes->list.size(), 0 ); for ( unsigned int i = 0; i < genotypes->list.size(); i++ ) { indices[i] = i; if ( genotypes->list[i]->count > highestCount ) highestCount = genotypes->list[i]->count; if ( genotypes->list[i]->adamdist > highestAD ) highestAD = genotypes->list[i]->adamdist; if ( genotypes->list[i]->brainzArch->ArchNeurons.size() > highestNeurons ) highestNeurons = genotypes->list[i]->brainzArch->ArchNeurons.size(); // calc total syns unsigned int totalSyns = 0; for ( unsigned int j = 0; j < genotypes->list[i]->brainzArch->ArchNeurons.size(); j++ ) totalSyns += genotypes->list[i]->brainzArch->ArchNeurons[j].ArchSynapses.size(); if ( totalSyns > highestSynapses ) highestSynapses = totalSyns; if ( genotypes->list[i]->bodyArch->archBodyparts.size() > highestNeurons ) highestNeurons = genotypes->list[i]->bodyArch->archBodyparts.size(); } // sort results for ( int i = genotypes->list.size(); i>0; i-- ) for ( int j = 0; j < i-1; j++ ) if ( genotypes->list[indices[j]]->count < genotypes->list[indices[j+1]]->count ) { unsigned keepI = indices[j]; indices[j] = indices[j+1]; indices[j+1] = keepI; } int titleNumWH = textprinter->getWidth( highestCount ); int titleColorWH = qwidth; int titlePosWH = textprinter->getWidth( genotypes->list.size() ); int titleAdWH = textprinter->getWidth( highestAD ); int titleNeuronsWH = textprinter->getWidth( highestNeurons ); int titleSynapsesWH = textprinter->getWidth( highestSynapses ); int titleBodypartsWH = textprinter->getWidth( highestBodyparts ); int colw1 = titlePosW; if ( colw1 < titlePosWH ) colw1 = titlePosWH; int colw2 = titleColorW; if ( colw2 < titleColorWH ) colw2 = titleColorWH; int colw3 = titleNumW; if ( colw3 < titleNumWH ) colw3 = titleNumWH; int colw4 = titleAdW; if ( colw4 < titleAdWH ) colw4 = titleAdWH; int colw5 = titleNeuronsW; if ( colw5 < titleNeuronsWH ) colw5 = titleNeuronsWH; int colw6 = titleSynapsesW; if ( colw6 < titleSynapsesWH ) colw6 = titleSynapsesWH; int colw7 = titleBodypartsW; if ( colw7 < titleBodypartsWH ) colw7 = titleBodypartsWH; int colspacer = 15; int col1 = colspacer; int col2 = col1+colspacer + colw1; int col3 = col2+colspacer + colw2; int col4 = col3+colspacer + colw3; int col5 = col4+colspacer + colw4; int col6 = col5+colspacer + colw5; int col7 = col6+colspacer + colw6; int col8 = col7+colspacer + colw7; v_space = -10 + titlebar; v_height = (genotypes->list.size() * (qheight+rowspacer)) + rowspacer + titlebar; v_width = col8; drawBackground(); drawBorders(); drawChildren(); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); textprinter->print( absPosition.x+col1, absPosition.y+19, titlePos ); textprinter->print( absPosition.x+col2, absPosition.y+19, titleColor ); textprinter->print( absPosition.x+col3, absPosition.y+19, titleNum ); textprinter->print( absPosition.x+col4, absPosition.y+19, titleAd ); textprinter->print( absPosition.x+col5, absPosition.y+19, titleNeurons ); textprinter->print( absPosition.x+col6, absPosition.y+19, titleSynapses ); textprinter->print( absPosition.x+col7, absPosition.y+19, titleBodyparts ); for ( unsigned int i=0; i < genotypes->list.size(); i++ ) { v_space += qheight + rowspacer; glColor4f(1.0f, 1.0f, 1.0f, 1.0f); textprinter->print( absPosition.x+col1, absPosition.y+v_space+9, i+1 ); textprinter->print( absPosition.x+col3, absPosition.y+v_space+9, genotypes->list[indices[i]]->count ); textprinter->print( absPosition.x+col4, absPosition.y+v_space+9, genotypes->list[indices[i]]->adamdist ); textprinter->print( absPosition.x+col5, absPosition.y+v_space+9, genotypes->list[i]->brainzArch->ArchNeurons.size() ); // total syns unsigned int totalSyns = 0; for ( unsigned int j = 0; j < genotypes->list[i]->brainzArch->ArchNeurons.size(); j++ ) totalSyns += genotypes->list[i]->brainzArch->ArchNeurons[j].ArchSynapses.size(); textprinter->print( absPosition.x+col6, absPosition.y+v_space+9, totalSyns ); textprinter->print( absPosition.x+col7, absPosition.y+v_space+9, genotypes->list[i]->bodyArch->archBodyparts.size() ); if ( *colormode ) glColor4f(genotypes->list[indices[i]]->speciescolor.r, genotypes->list[indices[i]]->speciescolor.g, genotypes->list[indices[i]]->speciescolor.b, genotypes->list[indices[i]]->speciescolor.a); else glColor4f(genotypes->list[indices[i]]->bodyArch->color.r, genotypes->list[indices[i]]->bodyArch->color.g, genotypes->list[indices[i]]->bodyArch->color.b, genotypes->list[indices[i]]->bodyArch->color.a); glBegin(GL_QUADS); glVertex2f(absPosition.x+col2, absPosition.y+v_space+qheight); glVertex2f(absPosition.x+col2, absPosition.y+v_space); glVertex2f(absPosition.x+col2+qwidth, absPosition.y+v_space); glVertex2f(absPosition.x+col2+qwidth, absPosition.y+v_space+qheight); glEnd(); glColor4f(1.0f, 1.0f, 1.0f, 0.0f); glBegin(GL_LINES); glVertex2f(absPosition.x+col2, absPosition.y+v_space+qheight); glVertex2f(absPosition.x+col2, absPosition.y+v_space); glVertex2f(absPosition.x+col2, absPosition.y+v_space); glVertex2f(absPosition.x+col2+qwidth, absPosition.y+v_space); glVertex2f(absPosition.x+col2+qwidth, absPosition.y+v_space); glVertex2f(absPosition.x+col2+qwidth, absPosition.y+v_space+qheight); glVertex2f(absPosition.x+col2+qwidth, absPosition.y+v_space+qheight); glVertex2f(absPosition.x+col2, absPosition.y+v_space+qheight); glEnd(); } } }
void GUIEngine::run() { // Always create clouds because they may or may not be // needed based on the game selected video::IVideoDriver *driver = RenderingEngine::get_video_driver(); cloudInit(); unsigned int text_height = g_fontengine->getTextHeight(); irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"), g_settings->getU16("screen_h")); while (RenderingEngine::run() && (!m_startgame) && (!m_kill)) { const irr::core::dimension2d<u32> ¤t_screen_size = RenderingEngine::get_video_driver()->getScreenSize(); // Verify if window size has changed and save it if it's the case // Ensure evaluating settings->getBool after verifying screensize // First condition is cheaper if (previous_screen_size != current_screen_size && current_screen_size != irr::core::dimension2d<u32>(0,0) && g_settings->getBool("autosave_screensize")) { g_settings->setU16("screen_w", current_screen_size.Width); g_settings->setU16("screen_h", current_screen_size.Height); previous_screen_size = current_screen_size; } //check if we need to update the "upper left corner"-text if (text_height != g_fontengine->getTextHeight()) { updateTopLeftTextSize(); text_height = g_fontengine->getTextHeight(); } driver->beginScene(true, true, video::SColor(255,140,186,250)); if (m_clouds_enabled) { cloudPreProcess(); drawOverlay(driver); } else drawBackground(driver); drawHeader(driver); drawFooter(driver); RenderingEngine::get_gui_env()->drawAll(); driver->endScene(); if (m_clouds_enabled) cloudPostProcess(); else sleep_ms(25); m_script->step(); #ifdef __ANDROID__ m_menu->getAndroidUIInput(); #endif } }
//========================================================================== // The 'main' function for the booter. Called by boot0 when booting // from a block device, or by the network booter. // // arguments: // biosdev - Value passed from boot1/NBP to specify the device // that the booter was loaded from. // // If biosdev is kBIOSDevNetwork, then this function will return if // booting was unsuccessful. This allows the PXE firmware to try the // next boot device on its list. void common_boot(int biosdev) { const char *val; char *bootFile; unsigned long adler32; int status; int cnt; bool quiet; bool firstRun = true; bool instantMenu; bool rescanPrompt; // Record the device that the booter was loaded from. gBIOSDev = biosdev & kBIOSDevMask; // Initialize boot info structure. initKernBootStruct(); // Setup VGA text mode. // Not sure if it is safe to call setVideoMode() before the // config table has been loaded. Call video_mode() instead. #if DEBUG printf("before video_mode\n"); #endif video_mode( 2 ); // 80x25 mono text mode. #if DEBUG printf("after video_mode\n"); #endif // First get info for boot volume. scanBootVolumes(gBIOSDev, 0); bvChain = getBVChainForBIOSDev(gBIOSDev); setBootGlobals(bvChain); // Load boot.plist config file status = loadSystemConfig(&bootInfo->bootConfig); if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet) { gBootMode |= kBootModeQuiet; } // Get verbosity at early stage to allow a quiet booter if (getValueForKey(kKernelFlagsKey, &val, &cnt, &bootInfo->bootConfig)) { if (getValueForBootKey(val, kVerboseModeFlag, &val, &cnt)) { gVerboseMode = true; } } // Scan and record the system's hardware information. scan_platform(); // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config if (getBoolForKey(kInsantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu) { firstRun = false; } // Loading preboot ramdisk if exists. loadPrebootRAMDisk(); // Disable rescan option by default gEnableCDROMRescan = false; // Enable it with Rescan=y in system config if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan) { gEnableCDROMRescan = true; } // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config. rescanPrompt = false; if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->bootConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) { gEnableCDROMRescan = promptForRescanOption(); } // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config. if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive) { gScanSingleDrive = true; } // Create a list of partitions on device(s). if (gScanSingleDrive) { scanBootVolumes(gBIOSDev, &bvCount); } else { scanDisks(gBIOSDev, &bvCount); } // Create a separated bvr chain using the specified filters. bvChain = newFilteredBVChain(0x80, 0xFF, kBVFlagSystemVolume|kBVFlagForeignBoot, kBVFlagEFISystem, &gDeviceCount); gBootVolume = selectBootVolume(bvChain); #if DEBUG printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags); printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags); getc(); #endif useGUI = true; // Override useGUI default getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig); if (useGUI) { if (gVerboseMode) { printf("Switching to GUI mode in 3 seconds...\n"); sleep(3); } initGUI(); /* XXX AsereBLN handle error */ } setBootGlobals(bvChain); // Parse args, load and start kernel. while (1) { const char *val; int len; int trycache; long flags, cachetime, kerneltime, exttime, sleeptime, time; int ret = -1; void *binary = (void *)kLoadAddr; bool tryresume; bool tryresumedefault; bool forceresume; config_file_t systemVersion; // system.plist of booting partition // additional variable for testing alternate kernel image locations on boot helper partitions. char bootFileSpec[512]; // Initialize globals. sysConfigValid = false; gErrors = false; getBootOptions(firstRun); firstRun = false; status = processBootOptions(); // Status==1 means to chainboot if ( status == 1 ) break; // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL if ( status == -1 ) { // gBootVolume == NULL usually means the user hit escape. if(gBootVolume == NULL) { freeFilteredBVChain(bvChain); if (gEnableCDROMRescan) rescanBIOSDevice(gBIOSDev); bvChain = newFilteredBVChain(0x80, 0xFF, kBVFlagSystemVolume|kBVFlagForeignBoot, kBVFlagEFISystem, &gDeviceCount); setBootGlobals(bvChain); } continue; } // Other status (e.g. 0) means that we should proceed with boot. if( bootArgs->Video.v_display == GRAPHICS_MODE ) drawBackground(); // Found and loaded a config file. Proceed with boot. // Turn off any GUI elements if( bootArgs->Video.v_display == GRAPHICS_MODE ) { gui.devicelist.draw = false; gui.bootprompt.draw = false; gui.menu.draw = false; gui.infobox.draw = false; drawBackground(); updateVRAM(); } // Find out which version mac os we're booting. if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion)) { if (getValueForKey(kProductVersion, &val, &len, &systemVersion)) { // getValueForKey uses const char for val // so copy it and trim strncpy(gMacOSVersion, val, MIN(len, 4)); gMacOSVersion[MIN(len, 4)] = '\0'; } } if (platformCPUFeature(CPU_FEATURE_EM64T)) { archCpuType = CPU_TYPE_X86_64; } else { archCpuType = CPU_TYPE_I386; } if (getValueForKey(karch, &val, &len, &bootInfo->bootConfig)) { if (strncmp(val, "i386", 4) == 0) { archCpuType = CPU_TYPE_I386; } } if (getValueForKey(k32BitModeFlag, &val, &len, &bootInfo->bootConfig)) { archCpuType = CPU_TYPE_I386; } if (!getBoolForKey (kWake, &tryresume, &bootInfo->bootConfig)) { tryresume = true; tryresumedefault = true; } else { tryresumedefault = false; } if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->bootConfig)) { forceresume = false; } if (forceresume) { tryresume = true; tryresumedefault = false; } while (tryresume) { const char *tmp; BVRef bvr; if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->bootConfig)) val="/private/var/vm/sleepimage"; // Do this first to be sure that root volume is mounted ret = GetFileInfo(0, val, &flags, &sleeptime); if ((bvr = getBootVolumeRef(val, &tmp)) == NULL) break; // Can't check if it was hibernation Wake=y is required if (bvr->modTime == 0 && tryresumedefault) break; if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) break; if (!forceresume && sleeptime+3<bvr->modTime) { printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime); break; } HibernateBoot((char *)val); break; } // Reset cache name. bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64); sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile); adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler)); if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) { strlcpy(gBootKernelCacheFile, val, len+1); } else { sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32); } // Check for cache file. trycache = (((gBootMode & kBootModeSafe) == 0) && !gOverrideKernel && (gMKextName[0] == '\0') && (gBootKernelCacheFile[0] != '\0')); verbose("Loading Darwin %s\n", gMacOSVersion); if (trycache) do { // if we haven't found the kernel yet, don't use the cache ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime); if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) { trycache = 0; break; } ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime); if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat) || (cachetime < kerneltime)) { trycache = 0; break; } ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime); if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory) && (cachetime < exttime)) { trycache = 0; break; } if (kerneltime > exttime) { exttime = kerneltime; } if (cachetime != (exttime + 1)) { trycache = 0; break; } } while (0); do { if (trycache) { bootFile = gBootKernelCacheFile; verbose("Loading kernel cache %s\n", bootFile); ret = LoadFile(bootFile); binary = (void *)kLoadAddr; if (ret >= 0) { break; } } bootFile = bootInfo->bootFile; // Try to load kernel image from alternate locations on boot helper partitions. sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile); ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); if (ret == -1) { // Not found any alternate locations, using the original kernel image path. strcpy(bootFileSpec, bootFile); } } } verbose("Loading kernel %s\n", bootFileSpec); ret = LoadThinFatFile(bootFileSpec, &binary); if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) { archCpuType = CPU_TYPE_I386; ret = LoadThinFatFile(bootFileSpec, &binary); } } while (0); clearActivityIndicator(); #if DEBUG printf("Pausing..."); sleep(8); #endif if (ret <= 0) { printf("Can't find %s\n", bootFile); if(gui.initialised) { sleep(1); drawBackground(); gui.devicelist.draw = true; gui.redraw = true; } } else { /* Won't return if successful. */ ret = ExecKernel(binary); } } // chainboot if (status==1) { if (getVideoMode() == GRAPHICS_MODE) { // if we are already in graphics-mode, setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode } } }
void UITextEdit::drawSelf(Fw::DrawPane drawPane) { if((drawPane & Fw::ForegroundPane) == 0) return; drawBackground(m_rect); drawBorder(m_rect); drawImage(m_rect); drawIcon(m_rect); //TODO: text rendering could be much optimized by using vertex buffer or caching the render into a texture int textLength = m_text.length(); const TexturePtr& texture = m_font->getTexture(); if(!texture) return; if(hasSelection()) { if(m_color != Color::alpha) { g_painter->setColor(m_color); for(int i=0;i<m_selectionStart;++i) g_painter->drawTexturedRect(m_glyphsCoords[i], texture, m_glyphsTexCoords[i]); } for(int i=m_selectionStart;i<m_selectionEnd;++i) { g_painter->setColor(m_selectionBackgroundColor); g_painter->drawFilledRect(m_glyphsCoords[i]); g_painter->setColor(m_selectionColor); g_painter->drawTexturedRect(m_glyphsCoords[i], texture, m_glyphsTexCoords[i]); } if(m_color != Color::alpha) { g_painter->setColor(m_color); for(int i=m_selectionEnd;i<textLength;++i) g_painter->drawTexturedRect(m_glyphsCoords[i], texture, m_glyphsTexCoords[i]); } } else if(m_color != Color::alpha) { g_painter->setColor(m_color); for(int i=0;i<textLength;++i) g_painter->drawTexturedRect(m_glyphsCoords[i], texture, m_glyphsTexCoords[i]); } // render cursor if(isExplicitlyEnabled() && m_cursorVisible && m_cursorInRange && isActive() && m_cursorPos >= 0) { assert(m_cursorPos <= textLength); // draw every 333ms const int delay = 333; int elapsed = g_clock.millis() - m_cursorTicks; if(elapsed <= delay) { Rect cursorRect; // when cursor is at 0 if(m_cursorPos == 0) cursorRect = Rect(m_rect.left()+m_padding.left, m_rect.top()+m_padding.top, 1, m_font->getGlyphHeight()); else cursorRect = Rect(m_glyphsCoords[m_cursorPos-1].right(), m_glyphsCoords[m_cursorPos-1].top(), 1, m_font->getGlyphHeight()); if(hasSelection() && m_cursorPos >= m_selectionStart && m_cursorPos <= m_selectionEnd) g_painter->setColor(m_selectionColor); else g_painter->setColor(m_color); g_painter->drawFilledRect(cursorRect); } else if(elapsed >= 2*delay) { m_cursorTicks = g_clock.millis(); } } g_painter->resetColor(); }
int titleScreen (Controller *userInput, int highestScore, int *numberOfLives, char *shipType) { char print = TRUE; Position star; int seed = 1; int i = 0; char score[50]; unsigned short *universianArray[SPLASH_FRAMES]; universianArray[0] = Universian1; universianArray[1] = Universian2; universianArray[2] = Universian3; universianArray[3] = Universian4; universianArray[4] = Universian5; universianArray[5] = Universian6; lcd_fillScreen(BLACK); memcpy((char*)LCD_FRAME_BUFFER,(char*)LCD_TEMP_BUFFER, 153600); // write temp buffer to fram buffer star.x = 0; star.y = 0; mdelay(300); playTheme(); for (i = 0; i < SPLASH_FRAMES; i++) { drawBackground(&star); lcd_BMP(DISPLAY_WIDTH/2, SPLASH_HEIGHT, -(0.5), -(0.5), universianArray[i], TRUE, FALSE); memcpy((char*)LCD_FRAME_BUFFER,(char*)LCD_TEMP_BUFFER, 153600); // write temp buffer to fram buffer mdelay(SPLASH_DELAY); } mdelay(1000); sprintf(score, "Highest Score: %9d", highestScore); while(!userInput->start) { // wait for start button drawBackground(&star); drawShip(INIT_SHIP_POS_X, INIT_SHIP_POS_Y, DEFAULT_SHIP_TYPE); lcd_BMP(DISPLAY_WIDTH/2, SPLASH_HEIGHT, -(0.5), -(0.5), Universian6, TRUE, FALSE); if(seed%BLINK_RATE == 0) { print = !print; } if(print) { lcd_putString(50, 300, "Press START to continue..."); //lcd_putString(50, SPLASH_HEIGHT+27, "Press START to continue..."); //lcd_putString(50, 300, "Press START to continue..."); } lcd_putString(50, SPLASH_HEIGHT+37, (unsigned char *)score); lcd_putString(50, SPLASH_HEIGHT+55, " Made by"); lcd_putString(50, SPLASH_HEIGHT+65, " James Slack-smith"); lcd_putString(50, SPLASH_HEIGHT+75, "Shanush Prema Thasarathan"); seed++; pollController(userInput); memcpy((char*)LCD_FRAME_BUFFER,(char*)LCD_TEMP_BUFFER, 153600); // write temp buffer to fram buffer /* if (userInput->select) { selectMenu(userInput, numberOfLives, shipType); } */ mdelay(100); pollController(userInput); } stopMusic(); mdelay(500); return seed; }
void QgsComposerLegend::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) { Q_UNUSED( itemStyle ); Q_UNUSED( pWidget ); if ( !painter ) return; if ( !shouldDrawItem() ) { return; } int dpi = painter->device()->logicalDpiX(); double dotsPerMM = dpi / 25.4; if ( mComposition ) { mSettings.setUseAdvancedEffects( mComposition->useAdvancedEffects() ); mSettings.setDpi( dpi ); } if ( mComposerMap ) { mSettings.setMmPerMapUnit( mComposerMap->mapUnitsToMM() ); // use a temporary QgsMapSettings to find out real map scale QgsMapSettings ms = mComposerMap->composition()->mapSettings(); ms.setOutputSize( QSizeF( mComposerMap->rect().width() * dotsPerMM, mComposerMap->rect().height() * dotsPerMM ).toSize() ); ms.setExtent( *mComposerMap->currentMapExtent() ); ms.setOutputDpi( dpi ); mSettings.setMapScale( ms.scale() ); } drawBackground( painter ); painter->save(); //antialiasing on painter->setRenderHint( QPainter::Antialiasing, true ); painter->setPen( QPen( QColor( 0, 0, 0 ) ) ); QgsLegendRenderer legendRenderer( mLegendModel2, mSettings ); legendRenderer.setLegendSize( rect().size() ); //adjust box if width or height is too small QSizeF size = legendRenderer.minimumSize(); if ( size.height() > rect().height() || size.width() > rect().width() ) { //need to resize box QRectF targetRect = QRectF( pos().x(), pos().y(), rect().width(), rect().height() ); if ( size.height() > targetRect.height() ) targetRect.setHeight( size.height() ); if ( size.width() > rect().width() ) targetRect.setWidth( size.width() ); //set new rect, respecting position mode and data defined size/position setSceneRect( evalItemRect( targetRect, true ) ); } legendRenderer.drawLegend( painter ); painter->restore(); //draw frame and selection boxes if necessary drawFrame( painter ); if ( isSelected() ) { drawSelectionBoxes( painter ); } }
int initGUI(void) { /*int val;*/ #ifdef EMBED_THEME config_file_t *config; config = &bootInfo->themeConfig; if (ParseXMLFile((char *)__theme_plist, &config->dictionary) != 0) { return 1; } #else int len; char dirspec[256]; getValueForKey( "Theme", &theme_name, &len, &bootInfo->bootConfig ); if ((strlen(theme_name) + 27) > sizeof(dirspec)) { return 1; } sprintf(dirspec, "/Extra/Themes/%s/theme.plist", theme_name); if (loadConfigFile(dirspec, &bootInfo->themeConfig) != 0) { return 1; } #endif // determine screen params from edid getResolution(&screen_params[0], &screen_params[1], &screen_params[2]); // Initalizing GUI strucutre. bzero(&gui, sizeof(gui_t)); // find best matching vesa mode for our requested width & height getGraphicModeParams(screen_params); // set our screen structure with the mode width & height gui.screen.width = screen_params[0]; gui.screen.height = screen_params[1]; // load graphics otherwise fail and return if (loadGraphics() == 0) { loadThemeValues(&bootInfo->themeConfig, true); colorFont(&font_small, gui.screen.font_small_color); colorFont(&font_console, gui.screen.font_console_color); // create the screen & window buffers if (createBackBuffer(&gui.screen) == 0) { if (createWindowBuffer(&gui.screen) == 0) { if (createWindowBuffer(&gui.devicelist) == 0) { if (createWindowBuffer(&gui.bootprompt) == 0) { if (createWindowBuffer(&gui.infobox) == 0) { if (createWindowBuffer(&gui.menu) == 0) { drawBackground(); // lets copy the screen into the back buffer memcpy( gui.backbuffer->pixels, gui.screen.pixmap->pixels, gui.backbuffer->width * gui.backbuffer->height * 4 ); setVideoMode( GRAPHICS_MODE, 0 ); gui.initialised = true; return 0; } } } } } } } return 1; }
void WallClock::paintEvent(QPaintEvent *) { static const int hourHand[8] = { -2, 18, 2, 18, 2, -60, -2, -60 }; static const int minuteHand[8] = { -2, 28, 2, 28, 2, -80, -2, -80 }; static const int secondHand[12] = {-1, 0, -1, -90, 1,-90, 1, 0, 4, 35, -4, 35}; // odmalowywuje t³o drawBackground(); // inicjalizacja paintera QPainter painter(this); initCoordinateSystem(painter); // Wyliczanie czasu i daty QTime time = m_dateTime.time(); QDate date = m_dateTime.date(); QString Str; QSize Size; if (timeOffset()!=0.0) { // Rysowanie tekstów - godziny painter.setFont(timeFont()); painter.setPen(timeColor()); Str = time.toString("hh:mm"); Size = painter.fontMetrics().size(Qt::TextSingleLine, Str ); painter.drawText( QPointF (Size.width() / -2.0, Size.height()+ timeOffset()) ,Str); } if (dateOffset()!=0.0) { // Rysowanie daty painter.setFont(dateFont()); painter.setPen(dateColor()); Str = date.toString("dd.MM.yyyy"); Size = painter.fontMetrics().size(Qt::TextSingleLine, Str); painter.drawText( QPointF(Size.width() / -2.0,static_cast<int>(0 - dateOffset())), Str); } if (dayOffset()!=0.0) { // Dzieñ tygodnia painter.setFont(dayFont()); painter.setPen(dayColor()); Str = date.toString("dddd"); Size = painter.fontMetrics().size(Qt::TextSingleLine, Str); painter.drawText( QPointF (Size.width() / -2.0,static_cast<int>( 0 - dayOffset())) , Str); } // rysowanie wskazówki godzin painter.setPen(Qt::NoPen); painter.setBrush(Qt::black); painter.save(); painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0))); painter.drawConvexPolygon(QPolygon(4, hourHand)); painter.restore(); // rysowanie minutnika painter.setBrush(Qt::black); painter.save(); painter.rotate(6.0 * (time.minute() + time.second() / 60.0)); painter.drawConvexPolygon(QPolygon(4, minuteHand)); painter.restore(); // Malowanie wskazówki sekundnika painter.setPen(Qt::NoPen); painter.setBrush(Qt::red); painter.save(); painter.rotate(6.0 * ( time.second())); // + time.msec() / 1000.0) ); painter.drawConvexPolygon(QPolygon(6, secondHand)); painter.restore(); // Kó³ko sekundnika painter.drawEllipse(-5,-5,10,10); }// paintEvent
int main(int argc, char *argv[]) { static SDL_Window *window; if(initWindow(&window, &renderer, argc, argv)) return 1; initVariables(WIDTH, HEIGHT); initTextures(); initFonts(); initInput(); //initHUD(); generateLevel(FIRSTLEVEL); hud = new Hud(); /*==============*/ /* Test Stuff */ /*==============*/ /*PhysicsEntity *goomba = new PhysicsEntity(getTexture("goomba"), 500, 50); goomba->patrolling = 1; Interactable *healthUp = new Interactable(getTexture("concrete"), 800, 500); healthUp->target = ply; healthUp->action = HEALTH_UP; Interactable *scrapUp = new Interactable(getTexture("sand"), 850, 500); scrapUp->target = ply; scrapUp->action = SCRAP_UP;*/ /*=================*/ /*End of Test Stuff*/ /*=================*/ int lastFrame = curtime_u() - 1; double dt; while(!quit) { if(DEBUG) fpsCounter(); // Calculate dt int curFrame = curtime_u(); if(lastFrame > curFrame) { dt = ((1000000 - lastFrame) + curFrame) / 1000000.0; } else { dt = (curFrame - lastFrame) / 1000000.0; } if(dt > 0.05) { dt = 0.05; // Clamp dt so objects don't have collision issues } lastFrame = curFrame; // =================== // Update if(nextlevel != "") { printf("Switching to level %s\n", nextlevel.c_str()); generateLevel(nextlevel); nextlevel = ""; } TimerRun(); for(int enti=0; enti<entsC; enti++) { if(ents[enti] == NULL) continue; ents[enti]->Update(dt); if(ents[enti]->isKilled) delete ents[enti]; } // ==================== // Drawing for(int rli=0; rli<RL_MAX; rli++) { if(rli == RL_BACKGROUND) { drawBackground(renderer, dt); continue; // Done in drawBackground } Drawable** layer = renderLayers[rli]; for(int enti=0; enti<renderLayersC[rli]; enti++) { if(layer[enti] == NULL) continue; layer[enti]->Draw(dt); } } // Flip render buffer SDL_RenderPresent(renderer); // Frame limiting, not needed if we're using vsync //SDL_Delay((1000 / 66) - (curtime_u() - lastFrame)/1000); } printf("\nShutting down...\n"); cleanLevel(); // Destroy old textures for(std::map<std::string, TextureData>::iterator it = blockTDs.begin(); it != blockTDs.end(); ++it) { SDL_DestroyTexture(it->second.texture); } blockTDs.clear(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); Mix_CloseAudio(); Mix_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
//----------------------------------------------------------------------------- /// Draw the markers void Profiler::draw() { video::IVideoDriver* driver = irr_driver->getVideoDriver(); std::stack<Marker> hovered_markers; drawBackground(); // Force to show the pointer irr_driver->showPointer(); int read_id = !m_write_id; // Compute some values for drawing (unit: pixels, but we keep floats for reducing errors accumulation) core::dimension2d<u32> screen_size = driver->getScreenSize(); const double profiler_width = (1.0 - 2.0*MARGIN_X) * screen_size.Width; const double x_offset = MARGIN_X*screen_size.Width; const double y_offset = (MARGIN_Y + LINE_HEIGHT)*screen_size.Height; const double line_height = LINE_HEIGHT*screen_size.Height; size_t nb_thread_infos = m_thread_infos.size(); const double factor = profiler_width / TIME_DRAWN_MS; // Get the mouse pos core::vector2di mouse_pos = GUIEngine::EventHandler::get()->getMousePos(); // For each thread: for(size_t i=0 ; i < nb_thread_infos ; i++) { // Draw all markers MarkerList& markers = m_thread_infos[i].markers_done[read_id]; if(markers.empty()) continue; MarkerList::const_iterator it_end = markers.end(); for(MarkerList::const_iterator it = markers.begin() ; it != it_end ; it++) { const Marker& m = *it; assert(m.end >= 0.0); core::rect<s32> pos((s32)( x_offset + factor*m.start ), (s32)( y_offset + i*line_height ), (s32)( x_offset + factor*m.end ), (s32)( y_offset + (i+1)*line_height )); // Reduce vertically the size of the markers according to their layer pos.UpperLeftCorner.Y += m.layer; pos.LowerRightCorner.Y -= m.layer; driver->draw2DRectangle(m.color, pos); // If the mouse cursor is over the marker, get its information if(pos.isPointInside(mouse_pos)) hovered_markers.push(m); } } // Draw the end of the frame { s32 x_sync = (s32)(x_offset + factor*m_time_between_sync); s32 y_up_sync = (s32)(MARGIN_Y*screen_size.Height); s32 y_down_sync = (s32)( (MARGIN_Y + (2+nb_thread_infos)*LINE_HEIGHT)*screen_size.Height ); driver->draw2DLine(core::vector2di(x_sync, y_up_sync), core::vector2di(x_sync, y_down_sync), video::SColor(0xFF, 0x00, 0x00, 0x00)); } // Draw the hovered markers' names gui::ScalableFont* font = GUIEngine::getFont(); if(font) { core::stringw text; while(!hovered_markers.empty()) { Marker& m = hovered_markers.top(); std::ostringstream oss; oss << m.name << " [" << (m.end-m.start) << " ms]" << std::endl; text += oss.str().c_str(); hovered_markers.pop(); } font->draw(text, MARKERS_NAMES_POS, video::SColor(0xFF, 0xFF, 0x00, 0x00)); } }
void QgsComposerTable::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) { Q_UNUSED( itemStyle ); Q_UNUSED( pWidget ); if ( !painter ) { return; } if ( mComposition->plotStyle() == QgsComposition::Print || mComposition->plotStyle() == QgsComposition::Postscript ) { //exporting composition, so force an attribute refresh //we do this in case vector layer has changed via an external source (eg, another database user) refreshAttributes(); } drawBackground( painter ); painter->save(); //antialiasing on painter->setRenderHint( QPainter::Antialiasing, true ); painter->setPen( Qt::SolidLine ); //now draw the text double currentX = mGridStrokeWidth; double currentY; QList<QgsComposerTableColumn*>::const_iterator columnIt = mColumns.constBegin(); int col = 0; double cellHeaderHeight = QgsComposerUtils::fontAscentMM( mHeaderFont ) + 2 * mLineTextDistance; double cellBodyHeight = QgsComposerUtils::fontAscentMM( mContentFont ) + 2 * mLineTextDistance; QRectF cell; for ( ; columnIt != mColumns.constEnd(); ++columnIt ) { currentY = mGridStrokeWidth; currentX += mLineTextDistance; cell = QRectF( currentX, currentY, mMaxColumnWidthMap[col], cellHeaderHeight ); //calculate alignment of header Qt::AlignmentFlag headerAlign = Qt::AlignLeft; switch ( mHeaderHAlignment ) { case FollowColumn: headerAlign = ( *columnIt )->hAlignment(); break; case HeaderLeft: headerAlign = Qt::AlignLeft; break; case HeaderCenter: headerAlign = Qt::AlignHCenter; break; case HeaderRight: headerAlign = Qt::AlignRight; break; } QgsComposerUtils::drawText( painter, cell, ( *columnIt )->heading(), mHeaderFont, mHeaderFontColor, headerAlign, Qt::AlignVCenter, Qt::TextDontClip ); currentY += cellHeaderHeight; currentY += mGridStrokeWidth; //draw the attribute values QList<QgsAttributeMap>::const_iterator attIt = mAttributeMaps.begin(); for ( ; attIt != mAttributeMaps.end(); ++attIt ) { cell = QRectF( currentX, currentY, mMaxColumnWidthMap[col], cellBodyHeight ); const QgsAttributeMap ¤tAttributeMap = *attIt; QString str = currentAttributeMap[ col ].toString(); QgsComposerUtils::drawText( painter, cell, str, mContentFont, mContentFontColor, ( *columnIt )->hAlignment(), Qt::AlignVCenter, Qt::TextDontClip ); currentY += cellBodyHeight; currentY += mGridStrokeWidth; } currentX += mMaxColumnWidthMap[ col ]; currentX += mLineTextDistance; currentX += mGridStrokeWidth; col++; } //and the borders if ( mShowGrid ) { QPen gridPen; gridPen.setWidthF( mGridStrokeWidth ); gridPen.setColor( mGridColor ); gridPen.setJoinStyle( Qt::MiterJoin ); painter->setPen( gridPen ); drawHorizontalGridLines( painter, mAttributeMaps.size() ); drawVerticalGridLines( painter, mMaxColumnWidthMap ); } painter->restore(); //draw frame and selection boxes if necessary drawFrame( painter ); if ( isSelected() ) { drawSelectionBoxes( painter ); } }
void QNeedleIndicator::paintEvent (QPaintEvent *event) { drawBackground(); drawNeedle(); QWidget::paintEvent(event); }
void MiniMap::showBookEntireMap(int showLevel) { // First Load Minimap TC & DATA if needed if(m_levels[showLevel].m_texContainer == NULL) { getData(showLevel); } if(!m_levels[showLevel].m_texContainer) { return; } GRenderer->SetRenderState(Renderer::DepthTest, false); float zoom = 250.f; Vec2f start(140.f, 120.f); Vec2f playerPos(0.f, 0.f); if(showLevel == ARX_LEVELS_GetRealNum(m_currentLevel)) { playerPos = computePlayerPos(zoom, showLevel); playerPos += start; } drawBackground(showLevel, Rect(0, 0, 345, 290), start, zoom); GRenderer->GetTextureStage(0)->setWrapMode(TextureStage::WrapRepeat); if(showLevel == ARX_LEVELS_GetRealNum(m_currentLevel)) { drawPlayer(3.f, playerPos, false); drawDetectedEntities(showLevel, start, zoom); } TexturedVertex verts[4]; for(int k = 0; k < 4; k++) { verts[k].color = Color(255, 255, 255, 255).toRGBA(); verts[k].rhw = 1; verts[k].p.z = 0.00001f; } Vec2f casePos(zoom / MINIMAP_MAX_X, zoom / MINIMAP_MAX_Z); float ratio = 1.f; for(size_t i = 0; i < m_mapMarkers.size(); i++) { if(m_mapMarkers[i].m_lvl != showLevel + 1) { continue; } Vec2f pos; pos.x = m_mapMarkers[i].m_pos.x * 8 * ratio * m_activeBkg->Xmul * casePos.x + start.x; pos.y = m_mapMarkers[i].m_pos.y * 8 * ratio * m_activeBkg->Zmul * casePos.y + start.y; float size = 5.f * ratio; verts[0].color = Color(255, 0, 0, 255).toRGBA(); verts[1].color = Color(255, 0, 0, 255).toRGBA(); verts[2].color = Color(255, 0, 0, 255).toRGBA(); verts[3].color = Color(255, 0, 0, 255).toRGBA(); verts[0].p.x = (pos.x - size) * g_sizeRatio.x; verts[0].p.y = (pos.y - size) * g_sizeRatio.y; verts[1].p.x = (pos.x + size) * g_sizeRatio.x; verts[1].p.y = (pos.y - size) * g_sizeRatio.y; verts[2].p.x = (pos.x + size) * g_sizeRatio.x; verts[2].p.y = (pos.y + size) * g_sizeRatio.y; verts[3].p.x = (pos.x - size) * g_sizeRatio.x; verts[3].p.y = (pos.y + size) * g_sizeRatio.y; verts[0].uv = Vec2f_ZERO; verts[1].uv = Vec2f_X_AXIS; verts[2].uv = Vec2f_ONE; verts[3].uv = Vec2f_Y_AXIS; const Rect mouseTestRect( verts[0].p.x, verts[0].p.y, verts[2].p.x, verts[2].p.y ); if(mouseTestRect.contains(Vec2i(DANAEMouse))) { if(!m_mapMarkers[i].m_text.empty()) { Rect bRect(140, 295, 140 + 205, 358); Rect::Num left = checked_range_cast<Rect::Num>((bRect.left) * g_sizeRatio.x); Rect::Num right = checked_range_cast<Rect::Num>((bRect.right) * g_sizeRatio.x); Rect::Num top = checked_range_cast<Rect::Num>((bRect.top) * g_sizeRatio.y); Rect::Num bottom = checked_range_cast<Rect::Num>((bRect.bottom) * g_sizeRatio.y); Rect rRect = Rect(left, top, right, bottom); long lLengthDraw = ARX_UNICODE_ForceFormattingInRect(hFontInGameNote, m_mapMarkers[i].m_text, rRect); ARX_UNICODE_DrawTextInRect(hFontInGameNote, (BOOKDEC + Vec2f(bRect.topLeft())) * g_sizeRatio, (BOOKDEC.x + float(bRect.right)) * g_sizeRatio.x, m_mapMarkers[i].m_text.substr(0, lLengthDraw), Color::none); } } if(m_mapMarkerTexCont == NULL) { m_mapMarkerTexCont = TextureContainer::Load("graph/interface/icons/mapmarker"); } GRenderer->SetTexture(0, m_mapMarkerTexCont); EERIEDRAWPRIM(Renderer::TriangleFan, verts, 4); } }
//========================================================================== // The 'main' function for the booter. Called by boot0 when booting // from a block device, or by the network booter. // // arguments: // biosdev - Value passed from boot1/NBP to specify the device // that the booter was loaded from. // // If biosdev is kBIOSDevNetwork, then this function will return if // booting was unsuccessful. This allows the PXE firmware to try the // next boot device on its list. void common_boot(int biosdev) { bool quiet; bool firstRun = true; bool instantMenu; bool rescanPrompt; int status; unsigned int allowBVFlags = kBVFlagSystemVolume | kBVFlagForeignBoot; unsigned int denyBVFlags = kBVFlagEFISystem; // Set reminder to unload the PXE base code. Neglect to unload // the base code will result in a hang or kernel panic. gUnloadPXEOnExit = true; // Record the device that the booter was loaded from. gBIOSDev = biosdev & kBIOSDevMask; // Initialize boot info structure. initKernBootStruct(); initBooterLog(); // Setup VGA text mode. // Not sure if it is safe to call setVideoMode() before the // config table has been loaded. Call video_mode() instead. #if DEBUG printf("before video_mode\n"); #endif video_mode( 2 ); // 80x25 mono text mode. #if DEBUG printf("after video_mode\n"); #endif // Scan and record the system's hardware information. scan_platform(); // First get info for boot volume. scanBootVolumes(gBIOSDev, 0); bvChain = getBVChainForBIOSDev(gBIOSDev); setBootGlobals(bvChain); // Load boot.plist config file status = loadChameleonConfig(&bootInfo->chameleonConfig); if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->chameleonConfig) && quiet) { gBootMode |= kBootModeQuiet; } // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->chameleonConfig) && instantMenu) { firstRun = false; } // Loading preboot ramdisk if exists. loadPrebootRAMDisk(); // Disable rescan option by default gEnableCDROMRescan = false; // Enable it with Rescan=y in system config if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->chameleonConfig) && gEnableCDROMRescan) { gEnableCDROMRescan = true; } // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config. rescanPrompt = false; if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->chameleonConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) { gEnableCDROMRescan = promptForRescanOption(); } // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config. if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->chameleonConfig) && gScanSingleDrive) { gScanSingleDrive = true; } // Create a list of partitions on device(s). if (gScanSingleDrive) { scanBootVolumes(gBIOSDev, &bvCount); } else { scanDisks(gBIOSDev, &bvCount); } // Create a separated bvr chain using the specified filters. bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount); gBootVolume = selectBootVolume(bvChain); // Intialize module system init_module_system(); #if DEBUG printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags); printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags); getchar(); #endif useGUI = true; // Override useGUI default getBoolForKey(kGUIKey, &useGUI, &bootInfo->chameleonConfig); if (useGUI && initGUI()) { // initGUI() returned with an error, disabling GUI. useGUI = false; } setBootGlobals(bvChain); // Parse args, load and start kernel. while (1) { bool tryresume, tryresumedefault, forceresume; bool useKernelCache = true; // by default try to use the prelinked kernel const char *val; int len, ret = -1; long flags, sleeptime, time; void *binary = (void *)kLoadAddr; char bootFile[sizeof(bootInfo->bootFile)]; char bootFilePath[512]; char kernelCacheFile[512]; // Initialize globals. sysConfigValid = false; gErrors = false; status = getBootOptions(firstRun); firstRun = false; if (status == -1) continue; status = processBootOptions(); // Status == 1 means to chainboot if ( status == 1 ) break; // Status == -1 means that the config file couldn't be loaded or that gBootVolume is NULL if ( status == -1 ) { // gBootVolume == NULL usually means the user hit escape. if (gBootVolume == NULL) { freeFilteredBVChain(bvChain); if (gEnableCDROMRescan) rescanBIOSDevice(gBIOSDev); bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount); setBootGlobals(bvChain); setupDeviceList(&bootInfo->themeConfig); } continue; } // Other status (e.g. 0) means that we should proceed with boot. // Turn off any GUI elements if ( bootArgs->Video.v_display == GRAPHICS_MODE ) { gui.devicelist.draw = false; gui.bootprompt.draw = false; gui.menu.draw = false; gui.infobox.draw = false; gui.logo.draw = false; drawBackground(); updateVRAM(); } // Find out which version mac os we're booting. getOSVersion(); if (platformCPUFeature(CPU_FEATURE_EM64T)) { archCpuType = CPU_TYPE_X86_64; } else { archCpuType = CPU_TYPE_I386; } if (getValueForKey(karch, &val, &len, &bootInfo->chameleonConfig)) { if (strncmp(val, "i386", 4) == 0) { archCpuType = CPU_TYPE_I386; } } if (getValueForKey(kKernelArchKey, &val, &len, &bootInfo->chameleonConfig)) { if (strncmp(val, "i386", 4) == 0) { archCpuType = CPU_TYPE_I386; } } // Notify modules that we are attempting to boot execute_hook("PreBoot", NULL, NULL, NULL, NULL); if (!getBoolForKey (kWake, &tryresume, &bootInfo->chameleonConfig)) { tryresume = true; tryresumedefault = true; } else { tryresumedefault = false; } if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->chameleonConfig)) { forceresume = false; } if (forceresume) { tryresume = true; tryresumedefault = false; } while (tryresume) { const char *tmp; BVRef bvr; if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->chameleonConfig)) val = "/private/var/vm/sleepimage"; // Do this first to be sure that root volume is mounted ret = GetFileInfo(0, val, &flags, &sleeptime); if ((bvr = getBootVolumeRef(val, &tmp)) == NULL) break; // Can't check if it was hibernation Wake=y is required if (bvr->modTime == 0 && tryresumedefault) break; if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) break; if (!forceresume && ((sleeptime+3)<bvr->modTime)) { #if DEBUG printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n", bvr->modTime-sleeptime); #endif break; } HibernateBoot((char *)val); break; } verbose("Loading Darwin %s\n", gMacOSVersion); getBoolForKey(kUseKernelCache, &useKernelCache, &bootInfo->chameleonConfig); if (useKernelCache) do { // Determine the name of the Kernel Cache if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) { if (val[0] == '\\') { len--; val++; } /* FIXME: check len vs sizeof(kernelCacheFile) */ strlcpy(kernelCacheFile, val, len + 1); } else { kernelCacheFile[0] = 0; // Use default kernel cache file } if (gOverrideKernel && kernelCacheFile[0] == 0) { verbose("Using a non default kernel (%s) without specifying 'Kernel Cache' path, KernelCache will not be used\n", bootInfo->bootFile); useKernelCache = false; break; } if (gMKextName[0] != 0) { verbose("Using a specific MKext Cache (%s), KernelCache will not be used\n", gMKextName); useKernelCache = false; break; } if (gBootFileType != kBlockDeviceType) useKernelCache = false; } while(0); do { if (useKernelCache) { ret = LoadKernelCache(kernelCacheFile, &binary); if (ret >= 0) break; } bool bootFileWithDevice = false; // Check if bootFile start with a device ex: bt(0,0)/Extra/mach_kernel if (strncmp(bootInfo->bootFile,"bt(",3) == 0 || strncmp(bootInfo->bootFile,"hd(",3) == 0 || strncmp(bootInfo->bootFile,"rd(",3) == 0) bootFileWithDevice = true; // bootFile must start with a / if it not start with a device name if (!bootFileWithDevice && (bootInfo->bootFile)[0] != '/') snprintf(bootFile, sizeof(bootFile), "/%s", bootInfo->bootFile); // append a leading / else strlcpy(bootFile, bootInfo->bootFile, sizeof(bootFile)); // Try to load kernel image from alternate locations on boot helper partitions. ret = -1; if ((gBootVolume->flags & kBVFlagBooter) && !bootFileWithDevice) { snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.P%s", bootFile); ret = GetFileInfo(NULL, bootFilePath, &flags, &time); if (ret == -1) { snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.R%s", bootFile); ret = GetFileInfo(NULL, bootFilePath, &flags, &time); if (ret == -1) { snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.S%s", bootFile); ret = GetFileInfo(NULL, bootFilePath, &flags, &time); } } } if (ret == -1) { // No alternate location found, using the original kernel image path. strlcpy(bootFilePath, bootFile, sizeof(bootFilePath)); } verbose("Loading kernel %s\n", bootFilePath); ret = LoadThinFatFile(bootFilePath, &binary); if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) { archCpuType = CPU_TYPE_I386; ret = LoadThinFatFile(bootFilePath, &binary); } } while (0); clearActivityIndicator(); #if DEBUG printf("Pausing..."); sleep(8); #endif if (ret <= 0) { printf("Can't find %s\n", bootFile); sleep(1); if (gBootFileType == kNetworkDeviceType) { // Return control back to PXE. Don't unload PXE base code. gUnloadPXEOnExit = false; break; } pause(); } else { /* Won't return if successful. */ ret = ExecKernel(binary); } } // chainboot if (status == 1) { // if we are already in graphics-mode, if (getVideoMode() == GRAPHICS_MODE) { setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode. } } if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) { nbpUnloadBaseCode(); } }
bool GdImageRenderer::create( const WaveformBuffer& buffer, const double start_time, const int image_width, const int image_height, const bool audacity) { if (start_time < 0.0) { error_stream << "Invalid start time: minimum 0\n"; return false; } else if (start_time > MAX_START_TIME) { error_stream << "Invalid start time: maximum " << MAX_START_TIME << '\n'; return false; } if (image_width < 1) { error_stream << "Invalid image width: minimum 1\n"; return false; } if (image_height < 1) { error_stream << "Invalid image height: minimum 1\n"; return false; } const int sample_rate = buffer.getSampleRate(); if (sample_rate > MAX_SAMPLE_RATE) { error_stream << "Invalid sample rate: " << sample_rate << " Hz, maximum " << MAX_SAMPLE_RATE << " Hz\n"; return false; } const int samples_per_pixel = buffer.getSamplesPerPixel(); if (samples_per_pixel > MAX_ZOOM) { error_stream << "Invalid zoom: maximum " << MAX_ZOOM << '\n'; return false; } image_ = gdImageCreateTrueColor(image_width, image_height); if (image_ == nullptr) { error_stream << "Failed to create image\n"; return false; } assert(sample_rate != 0); assert(samples_per_pixel != 0); image_width_ = image_width; image_height_ = image_height; start_time_ = start_time; sample_rate_ = buffer.getSampleRate(); samples_per_pixel_ = samples_per_pixel; start_index_ = secondsToPixels(start_time); output_stream << "Image dimensions: " << image_width_ << "x" << image_height_ << " pixels" << "\nSample rate: " << sample_rate_ << " Hz" << "\nSamples per pixel: " << samples_per_pixel_ << "\nStart time: " << start_time_ << " seconds" << "\nStart index: " << start_index_ << "\nBuffer size: " << buffer.getSize() << std::endl; initColors(audacity); drawBackground(); drawBorder(); drawWaveform(buffer); drawTimeAxisLabels(); return true; }
void QgsComposerLegend::paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget ) { Q_UNUSED( itemStyle ); Q_UNUSED( pWidget ); if ( !painter ) return; if ( !shouldDrawItem() ) { return; } if ( mFilterAskedForUpdate ) { mFilterAskedForUpdate = false; doUpdateFilterByMap(); } int dpi = painter->device()->logicalDpiX(); double dotsPerMM = dpi / 25.4; if ( mComposition ) { mSettings.setUseAdvancedEffects( mComposition->useAdvancedEffects() ); mSettings.setDpi( dpi ); } if ( mComposerMap ) { mSettings.setMmPerMapUnit( mComposerMap->mapUnitsToMM() ); // use a temporary QgsMapSettings to find out real map scale QSizeF mapSizePixels = QSizeF( mComposerMap->rect().width() * dotsPerMM, mComposerMap->rect().height() * dotsPerMM ); QgsRectangle mapExtent = *mComposerMap->currentMapExtent(); QgsMapSettings ms = mComposerMap->mapSettings( mapExtent, mapSizePixels, dpi ); mSettings.setMapScale( ms.scale() ); } mInitialMapScaleCalculated = true; QgsLegendRenderer legendRenderer( mLegendModel, mSettings ); legendRenderer.setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() ); //adjust box if width or height is too small if ( mSizeToContents ) { QSizeF size = legendRenderer.minimumSize(); if ( mForceResize ) { mForceResize = false; //set new rect, respecting position mode and data defined size/position QRectF targetRect = QRectF( pos().x(), pos().y(), size.width(), size.height() ); setSceneRect( evalItemRect( targetRect, true ) ); } else if ( size.height() > rect().height() || size.width() > rect().width() ) { //need to resize box QRectF targetRect = QRectF( pos().x(), pos().y(), rect().width(), rect().height() ); if ( size.height() > targetRect.height() ) targetRect.setHeight( size.height() ); if ( size.width() > rect().width() ) targetRect.setWidth( size.width() ); //set new rect, respecting position mode and data defined size/position setSceneRect( evalItemRect( targetRect, true ) ); } } drawBackground( painter ); painter->save(); //antialiasing on painter->setRenderHint( QPainter::Antialiasing, true ); painter->setPen( QPen( QColor( 0, 0, 0 ) ) ); if ( !mSizeToContents ) { // set a clip region to crop out parts of legend which don't fit QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() ); painter->setClipRect( thisPaintRect ); } legendRenderer.drawLegend( painter ); painter->restore(); //draw frame and selection boxes if necessary drawFrame( painter ); if ( isSelected() ) { drawSelectionBoxes( painter ); } }
void QgsPaperItem::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) { Q_UNUSED( itemStyle ); Q_UNUSED( pWidget ); if ( !painter ) { return; } drawBackground( painter ); //draw grid if ( mComposition ) { if ( mComposition->snapToGridEnabled() && mComposition->plotStyle() == QgsComposition::Preview && mComposition->snapGridResolution() > 0 ) { int gridMultiplyX = ( int )( mComposition->snapGridOffsetX() / mComposition->snapGridResolution() ); int gridMultiplyY = ( int )( mComposition->snapGridOffsetY() / mComposition->snapGridResolution() ); double currentXCoord = mComposition->snapGridOffsetX() - gridMultiplyX * mComposition->snapGridResolution(); double currentYCoord; double minYCoord = mComposition->snapGridOffsetY() - gridMultiplyY * mComposition->snapGridResolution(); if ( mComposition->gridStyle() == QgsComposition::Solid ) { painter->setPen( mComposition->gridPen() ); //draw vertical lines for ( ; currentXCoord <= rect().width(); currentXCoord += mComposition->snapGridResolution() ) { painter->drawLine( QPointF( currentXCoord, 0 ), QPointF( currentXCoord, rect().height() ) ); } //draw horizontal lines currentYCoord = minYCoord; for ( ; currentYCoord <= rect().height(); currentYCoord += mComposition->snapGridResolution() ) { painter->drawLine( QPointF( 0, currentYCoord ), QPointF( rect().width(), currentYCoord ) ); } } else //'Dots' or 'Crosses' { QPen gridPen = mComposition->gridPen(); painter->setPen( gridPen ); painter->setBrush( QBrush( gridPen.color() ) ); double halfCrossLength = mComposition->snapGridResolution() / 6; for ( ; currentXCoord <= rect().width(); currentXCoord += mComposition->snapGridResolution() ) { currentYCoord = minYCoord; for ( ; currentYCoord <= rect().height(); currentYCoord += mComposition->snapGridResolution() ) { if ( mComposition->gridStyle() == QgsComposition::Dots ) { QRectF pieRect( currentXCoord - gridPen.widthF() / 2, currentYCoord - gridPen.widthF() / 2, gridPen.widthF(), gridPen.widthF() ); painter->drawChord( pieRect, 0, 5760 ); } else if ( mComposition->gridStyle() == QgsComposition::Crosses ) { painter->drawLine( QPointF( currentXCoord - halfCrossLength, currentYCoord ), QPointF( currentXCoord + halfCrossLength, currentYCoord ) ); painter->drawLine( QPointF( currentXCoord, currentYCoord - halfCrossLength ), QPointF( currentXCoord, currentYCoord + halfCrossLength ) ); } } } } } } }
void QgsComposerPicture::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) { Q_UNUSED( itemStyle ); Q_UNUSED( pWidget ); if ( !painter ) { return; } if ( !shouldDrawItem() ) { return; } drawBackground( painter ); //int newDpi = ( painter->device()->logicalDpiX() + painter->device()->logicalDpiY() ) / 2; //picture resizing if ( mMode != Unknown ) { double boundRectWidthMM; double boundRectHeightMM; QRect imageRect; if ( mResizeMode == QgsComposerPicture::Zoom || mResizeMode == QgsComposerPicture::ZoomResizeFrame ) { boundRectWidthMM = mPictureWidth; boundRectHeightMM = mPictureHeight; imageRect = QRect( 0, 0, mImage.width(), mImage.height() ); } else if ( mResizeMode == QgsComposerPicture::Stretch ) { boundRectWidthMM = rect().width(); boundRectHeightMM = rect().height(); imageRect = QRect( 0, 0, mImage.width(), mImage.height() ); } else if ( mResizeMode == QgsComposerPicture::Clip ) { boundRectWidthMM = rect().width(); boundRectHeightMM = rect().height(); int imageRectWidthPixels = mImage.width(); int imageRectHeightPixels = mImage.height(); imageRect = clippedImageRect( boundRectWidthMM, boundRectHeightMM, QSize( imageRectWidthPixels, imageRectHeightPixels ) ); } else { boundRectWidthMM = rect().width(); boundRectHeightMM = rect().height(); imageRect = QRect( 0, 0, rect().width() * mComposition->printResolution() / 25.4, rect().height() * mComposition->printResolution() / 25.4 ); } painter->save(); //antialiasing on painter->setRenderHint( QPainter::Antialiasing, true ); //zoom mode - calculate anchor point and rotation if ( mResizeMode == Zoom ) { //TODO - allow placement modes with rotation set. for now, setting a rotation //always places picture in center of frame if ( !qgsDoubleNear( mPictureRotation, 0.0 ) ) { painter->translate( rect().width() / 2.0, rect().height() / 2.0 ); painter->rotate( mPictureRotation ); painter->translate( -boundRectWidthMM / 2.0, -boundRectHeightMM / 2.0 ); } else { //shift painter to edge/middle of frame depending on placement double diffX = rect().width() - boundRectWidthMM; double diffY = rect().height() - boundRectHeightMM; double dX = 0; double dY = 0; switch ( mPictureAnchor ) { case UpperLeft: case MiddleLeft: case LowerLeft: //nothing to do break; case UpperMiddle: case Middle: case LowerMiddle: dX = diffX / 2.0; break; case UpperRight: case MiddleRight: case LowerRight: dX = diffX; break; } switch ( mPictureAnchor ) { case UpperLeft: case UpperMiddle: case UpperRight: //nothing to do break; case MiddleLeft: case Middle: case MiddleRight: dY = diffY / 2.0; break; case LowerLeft: case LowerMiddle: case LowerRight: dY = diffY; break; } painter->translate( dX, dY ); } } else if ( mResizeMode == ZoomResizeFrame ) { if ( !qgsDoubleNear( mPictureRotation, 0.0 ) ) { painter->translate( rect().width() / 2.0, rect().height() / 2.0 ); painter->rotate( mPictureRotation ); painter->translate( -boundRectWidthMM / 2.0, -boundRectHeightMM / 2.0 ); } } if ( mMode == SVG ) { mSVG.render( painter, QRectF( 0, 0, boundRectWidthMM, boundRectHeightMM ) ); } else if ( mMode == RASTER ) { painter->drawImage( QRectF( 0, 0, boundRectWidthMM, boundRectHeightMM ), mImage, imageRect ); } painter->restore(); } //frame and selection boxes drawFrame( painter ); if ( isSelected() ) { drawSelectionBoxes( painter ); } }