Printing on a Color StyleWriter

Posted by pulkomandy on Fri Jul 14 21:02:32 2017  •  Comments (0)  • 

Je suis l'heureux propriétaire d'une imprimante Apple Color StyleWriter 2400. Je l'ai récupérée il y a fort longtemps avec un lot de Macintosh qui partaient à la poubelle.

Cette imprimante date de 1994, elle a été vendue par Apple mais le matériel est conçu par Canon. On peut donc utiliser des cartouces de cette marque.

Et donc, après une dizaine d'année à traîner dans un coin de mon bazar, il était temps de remettre cette imprimante en service!

Étape 1: la brancher

Une particularité des imprimantes Apple de cette époque est d'utiliser un port série. En effet, les Macintosh n'avaient pas de port parallèle comme les PC. En plus de ça, pour gagner de la place sur la face arrière de ses machines, Apple a très vite laissé tombé le connecteur DE-9 pour utiliser à la place une mini-DIN. Rien de grave: on trouve le cablage par exemple ici. J'ai coupé un cable série Apple en 2 et j'y ai soudé un connecteur DE-9, et c'est parti!

Étape 2: les pilotes

Normalement, cette imprimante est sensée fonctionner avec un Macintosh de 1994. Évidement il n'y a pas de pilotes pour les systèmes plus récents. Mais, on a de la chance, quelqu'un a fait une grande partie du travail avec lpstyl. C'est pas vraiment un driver, plutôt un exécutable qui sait juste prendre une image dans un format bien précis, et l'imprimer. C'est prévu pour s'intégrer dans une chaîne d'impression UNIX, entre d'autres programmes qui vont convertir le fichier à imprimer en image, et le port série de l'ordinateur.

J'ai donc récupéré les sources et fait quelques ajustements pour que ça marche avec Haiku, mon système d'exploitation préféré. Et surtout, j'ai du ajouter quelques délais, car le code d'origine est trop rapide sur mon PC et n'arrive pas bien à se synchroniser avec l'imprimante. Bref, après quelques ajustements, l'imprimante prend une feuille de papier, le chariot se met en mouvement et… à la fin, j'ai une page blanche.

Étape 3: l'encre

Ben oui forcément, après 10 ans à dormir, la cartouche d'encre est toute sèche. Hereusement sur ce modèle, on peut remplacer le réservoir d'encre mais aussi la tête d'impression (qui est elle aussi pleine d'encre sèche et donc bonne à jeter). Par contre, Canon ne fabrique plus ces têtes d'impression (on trouve facilement les cartouches avec seulement le réservoir d'encre). J'ai fini par trouver un ensemble tête d'impression + cartouches noir et couleur pour pas trop cher chez un vendeur anglais. J'avais un peu peur que l'encre soit sèche après probablement 10 ans passés sur une étagère. Mais non, les cartouches sont vendues dans un emballage scellé sous pression, et avec un petit feuillet plastique de protection.

Du coup, j'ai juste eu besoin d'installer la nouvelle cartouche et j'ai enfin pu imprimer une page de test.

Étape 4: intégration avec Haiku

Bon, c'est bien joli d'imprimer une image de test, mais je peux toujours pas cliquer sur fichier/imprimer dans mes programmes et obtenir une sortie sur papier directement. Il va falloir intégrer ça proprement.

Ce sera l'occasion pour moi d'apprendre à écrire un driver d'imprimante pour Haiku, et probablement de débugger quelques petites choses dans le support de l'impression en général. De ce que j'ai vu, ça marche pas encore super bien.

Conclusion

Cette imprimante est plutôt solide et efficace, et elle fonctionnera sans doute encore de nombreuses années (tant que j'arrive à trouver des cartouches d'encre, en tout cas). Et autre bonne nouvelle, contrairement à la version Canon, il n'y a pas de compteur de pages qui met l'imprimante HS après un certain nombre de pages imprimées (soi-disant parce qu'il y a un réservoir d'encre usée qu'on ne peut pas vider dedans...).

J'ai donc économisé l'achat d'une imprimante neuve et qui aurait probablement duré moins longtemps.

MesagEase Keyboard

Posted by pulkomandy on Sat Apr 1 13:28:43 2017  •  Comments (0)  • 

I recently gave up on using my old "phonebooth" dumb-phones and switched to… a 10 year old Galaxy S. What an upgrade!

I of course updated it to CyanogenMod, which runs quite well on this device and allows me to get a reasonably "recent" Android version (4.4, which is old, but still compatible with most apps).

Anyway, the main problem with that phone was the keyboard. I was never very good at typing with the numeric keyboard on old phones, but for some time I have been using a Nokia phone with a physical keyboard, which was quite nice. While the tocuhscreen-keyboard on Android makes place for a much larger display, which is a very good thing, it has awfully small keys and no feedback. It also tries to auto-correct me in a way that is sometimes useful, sometimes not correcting obvious mistakes, but also sometimes trying to correct where it really shouldn't or when I'm already trying to correct myself.

As you may know, the QWERTY layout was designed as a workaround for mechanical limitations of early typewriters. There is no reason at all to continue to use it today on physical keyboards, and even less on smartphone virtual ones. Surely, there had to be something better!

After some research, I found the MessagEase keyboard. It is, as expected, an input replacement for Android. The keyboard has just 9 keys, but each of them has 9 chars depending on the gesture you make. It is easy to learn (even if at first you have to do a bit of hunt and peck), and allows quite fast typing. It also has some interesting features, for example the keyboard can be made partially transparent, so you can still see a little of what's under it (not all applications put something under it, but some do). It is also very configurable (you can move characters around on the keyboard and change many other settings).

After a few days of training, I can type at a reasonable speed, and much less typos than with the normal keyboard. So this is something I would recommend to everyone using their phone display as a keyboard. Forget about QWERTY before it is too much hardwired into your muscle memory there!

Now, I need to compare this with Graffiti, which is now available on Android. I remember using that in the Palm days, but I didn't do a lot of writing with it, so I don't remember how fast it could go. Also, using it without a stylus will probably be quite different. But, I should give it a try and see what happens.

Bitbox laptop

Posted by pulkomandy on Tue Nov 24 22:20:55 2015  •  Comments (1)  • 

This article is about the bitbox. If you don't know about it yet, click the link and read about it.

I got my bitbox last year, and it quickly became quite annoying that each time I wanted to use it, I had to unplug the LCD from my PC, locate my gamepad, an USB cable to power it, remember which of the USB ports the gamepad must be plugged to, etc. I also always feared that while carrying the bitbox in my backpack, I would bend a pin on one of the connectors or something.

Well, I solved these issues. I could have gone with a 3D printed case and whatnot, but I went with the simpler solution: make a laptop-like case using some easily hackable devices!

the bitbox laptop!

You can easily build one yourself. You need the following parts (dx.com links included):

Assembply instructions:

  • Remove the backpanel from the TV so it is thin enough to fit the tablet support in the keyboard.
  • Cut some holes in the keyboard cover to make space for the bog capacitors on the TV PCB (easily done, the keyboard cover is only thick cardboard)
  • Locate the 5V regulator on the TV PCB and solder a wire there to power the bitbox
  • Plug the keyboard and TV to the bitbox (you need the VGA gender changer here), and glue the bitbox next to the display (they both fit)
  • Enjoy!

There is some room for improvement. The setup currently doesn't include a battery (I wanted to use an USB "power bank", but the LCD display needs 12V), and the VGA connector is needlessly bulky, especially with the gender changer. I could solder the wires directly to the bitbox and ignore the connector, but I like to be able to remove the bitbox from this. Maybe I should add an HE10 or some other connector for the display output.

So, what is it useful for? Well, you can run all the bitbox games and apps (as long as they can be used with a keyboard). The ZX works fine, but I would prefer a more friendly on-line development interface (Amstrad CPC emulation was suggested, but I think a better idea is a native BASIC/Lua/Forth/Squirrel/whatever). One can also run the chiptracker there, but that needs audio output, which the LCD I used unfortunately doesn't include.

Maybe someone can suggest a reasonably flat and small loudspeaker to fit into this? And what about the battery? There are some 12V batteries on dx but they will need some charge control. Or should I use my USB thing with a boost converter?

Radeon 7000 on Windows 7

Posted by pulkomandy on Mon Aug 18 22:02:04 2014  •  Comments (0)  • 

As you know, Windows XP is EOL now. However, I'm still using that machine I assembled in 2003 as my only Windows computer, and I don't plan to change that. So I went ahead ans upgraded it to Win7.

Everything works fine, except the video card. Windows will complain that it needs a DirectX9 card. I know such a thing can be found even for my old AGP motherboard, but that's more money than I want to spend.

AMD won't provide drivers for such an old card for the new windows (Vista and 7). You can force-install the XP driver, and it will mostly work, but the system will BSOD on shutdown. Not so nice.

The solution is simple, once you have found it. The drivers for Windows Server 2008 will work perfectly. In the case of my Radeon 7000, these can be downloaded from Dell's FTP.

Note that the installer won't work, but using the inf files provided with the driver will go fine. And I now have my PC running as it should again.

I should look into Windows Server drivers for more of my hardware. It looks much less bloatware-enabled than the mainstream versions and gets the job done.

Reviving a Turbo-XT

Posted by pulkomandy on Tue Aug 5 16:33:51 2014  •  Comments (0)  • 

How I got an XT motherboard

This week I got an old PC/XT clone motherboard back in working order.

I had this board on my parts bin for some years. My cousin had found a PC/XT on the sidewalk, probably some company threw it away when the power supply failed. Unfortunately, it came with no keyboard, monitor, or even floppy drive.

Inside the original box (a big desktop-style one) was the huge and heavy power supply, the motherboard, an Hercules compatible card, a floppy controller, an MFM hard disk and its controller card.

I had already tried replacing the power supply with a standard AT one (the connectors are similar enough) and I could hear the PC speaker beep, so I knew the POST test was passing, however, without the monitor and keyboard, I couldn't do much more. The hard drive would not spin up. I only kept the motherboard and the 3 expansion cards, and got rid of the hard drive, case and power supply.

The computer comes with an Hercules compatible video card. This is a monochrome display, but more importantly it uses the same refresh rates as MDA: 50Hz vertical and 18.6kHz horizontal. This does not match the 15.6kHz used by TVs and CGA, nor the 31.5kHz used by VGA. Attempts to use ISA VGA cards on this motherboard weren't very succesful. So I let the boards sleep for a few years in my parts bin.

Seeing it boot

Last month, the "8088 domination" demo was released. This got me thinking about this motherboard again and I decided to see if I could do something useful with it. I installed it in a baby-AT tower case which takes less space than the original and started researching a solution for using the MDA card. I first thought of connecting it to my CTM640, which is normally a 15kHz monitor, but can be adjusted a bit using a potentiometer. I had to build a sync mixer to merge the horizontal and vertical sync signals (I simply XORed them together using 74LSxx chips). I could get some garbage on screen but the sync didn't work, so it was just unreadable text. However I knoew the MDA card was worknig properly, as I could see some generated video and check the sync lines with an oscilloscope.

I started looking for scanrate converters, but it seems so far there is no cheap solution that officially supports MDA. It's possible to find some VGA to composite or VGA to HDMI converters, and I think some of these may be compatible. However, while researching those, I noticed they work pretty much like the input section of most modern LCD displays. This gave me the idea to test my LCD (which is actually a TV with SCART, VGA and HDMI outputs) to see which frequency range it would accept.

I booted Haiku and used the screenmode command to set a custom video mode using a modeline. I couldn't find the exact timings for the MDA/Hercules cards online, however they are fairly easy to compute from the CRTC settings, which I found on John Elliot's page about Hercules cards (you just multiply the character-based settings by the character horizontal or vertical size). It turns out this LCD will handle a 18kHz HSync just fine.

The next step was wiring an MDA to VGA connector adapter. The wiring is straightforward, I connected the "monochrome" output from the video card to the green channel, and the "intensity" to the red one. The VGA port should need a 0.7v signal, but it turns out my LCD accepts the 5V TTL just fine (it's a Linetech LF1912HD01, but that brand or model probably disappeared from stores already). So I could finally see the bootscreen!

User input needed

Ok, without a keyboard, being able to boot DOS isn't so useful. And as you should know, the PC and PC/XT use a different keyboard protocol from later models, so using a standard PS/2 keyboard directly is not possible.

This is a long-solved problem, with the guis at the Vintage Computer Forum having an adapter built around a small PIC12 chip. But I don't like PICs and prefer AVRs. There is an AVR version of the adapter, but the code is big and clumsy, where a small and simple one would do the job just as well.

So I designed my own keyboard adapter. The code is C and should be fairly readable. It uses the same PS/2 library I used earlier for my PCW and Amiga keyboard adapters. The lib had some problems and this was a good occasion to review it, clean it up, and do some more testing. On the XT side, things are rather simple as I just need to send the single byte keycodes with a standard clock signal. This is implemented on the XT side using a 74LS shift register, which is quite flexible on the timings.

So, I now have the adapter (named XTK) working, on two different boards I had lying around. One uses an ATMega8 or ATMega48, the other uses an ATTiny2313. You can find the code at the avrstuff repository. However, for the final version of this I plan to use an ATTiny13 and fit the whole adapter circuit inside the DIN connector. I want to get my prototyping boarsd back, and a small integrated circuit like this will be much less fragile.

While I was at it, I also replaced a burnt LED in my Olivetti keyboard. It has a nice yellow caps lock LED again. But I didn't update the PS/2 library so it controls the keyboard LEDs yet. That will come later.

Mass storage

Ok, I fitted a 5"1/4 floppy drive in the machine so I could boot DOS and test the keyboard at a prompt. This is working quite well, but swapping floppies gets annoying and I'd rather keep my other floppy drives for other projects. This PC originally came with an MFM or RLL hard disk, which was broken when I got my hands on it. Replacements are hard to find, and they are heavy and noisy. Instead, I plan to use a compact flash card. I could buy the amazing XT-CF or XT-IDE boards, but even if they are quite cheap, it's more money than I want to waste on this computer. So let's see if I can continue doing things with just my parts bin.

First, I need a way to connect the "XTIDE universal ROM" so I can access my CF card using the usual DOS interrupts. My motherboard has 6 ROMs slots on it like the original 5150 PC. Only one is used for the BIOS, the next 4 are for the IBM BASIC, and the last one is for an expansion ROM. I used this one for the XTIDE ROM. On this motherboard the ROMs have a standard pinout, so I could easily put the XTIDE universal ROM on a 27C256 chip (copied 4 times to make sure the system can see it). After some hacking on my EPROM programmer, I got it to reliably program this in the ROM. So that's one problem solved.

I also need to connect the compact flash card. It turns out I can use the IDE port on a sound card, and XTIDE can set the CF card to 8-bit mode to avoid the use of the 16-bit bus, which is of course not wired on my machine. This is the same trick I use on my CF adapter for CPC. (you need XTIDE version 2 to use this feature).

However, I need a non-PNP card with an IDE port for this to work. The BIOS doesn't know how to initialize PNP cards, and if I wanted to do it using the manufacturer provided drivers (assuming they can run on a 8088), I'd have to boot DOS first. Time to dig out that Sound Blaster 16 which is the only non-PNP card I have around. Mine comes with an IDE port which I set to address 1F0.

With the sound card and the CF adapter plugged, the XTIDE installation tool detected everything just fine and I could prepare the ROM file suitable for my machine. I saved this back to disc (my UVPROM can't be programmed on the fly on the motherboard like the flash chip on XTIDE would), got that file back to my other DOS PC where I could finally put it on the ROM. I seated that ROM in the XT and could see the XTIDE welcome message. Some FDISK later I could boot DOS from that compact flash, it works quite well and DOS boots in less than a second (but there aren't much drivers to load).

The software!

Well, now that the thing is running... what to do with it? I ran through my 5"1/4 floppies and found that a lot of the software there is meant to use with either CGA, Tandy PCJr, or some later video card. But there are some games for the Hercules card as well. Of course none of those use the Sound Blaster (even in AdLib mode), they all go for the PC speaker. I had more success with the tools such as QBasic and Turbo Pascal, but I'll probably cross compile things I want to run on the machine.

An obvious thing to do on a 8088 based machine is to run "8088 Corruption". I thought this required a CGA card, but MDA support is now available. However, and as pointed out by Trixter, I found that the Sound Blaster 16 wouldn't work on a 8088 based box because it needs some tools in the autoexec to initialize it. However, I found a workaround to this once again on the Vintage Computer forums. A simple DEBUG script can be used to initialize the card.

o 224 80
o 225 02
o 224 81
o 225 02
q

I added this to my autoexec.bat, and it worked! I can now use the card (as a Sound Blaster 2.0, the 16-bit DMA obviously won't work). The mixer volume is quite low, so I may have to extend this debug script or try to run one of the mixer tools if I can find one that runs on the 8088. Or I could get a Nec V20 which would run all this software fine.

Getting it on the network!

I tried using a 3Com Etherlink III as an extra extension ROM slot. That didn't work, but I stopped messing with it when I noticed that the motherboard already had a slot for XTIDE. Maybe I can add some ethernet connectivity to this machine with this card. However, 3COM tools to configure it don't seem to detect it. I may need an alternative driver that supports the 8088, just like for the sound card.

Configuring MSYS for real work

Posted by pulkomandy on Mon Jul 16 21:18:16 2012  •  Comments (0)  • 

People always request Windows binaries for some of my project, so I'm using a fairly complete MinGW/MSYS setup to get this done. However, the default setup for MSYS is not very efficient and doesn't manage to blend well in a Windows install (which is kind of expected). Here are some tricks to make it behave a bit better.

Bash prompt

An improvement on my existing "exit-status-colored" bash prompt. In Windows the path get long very easily (starting with "/c/Document and Settings/user/My Documents" before you've even got anywhere!). So here's a bash prompt that looks just like the previous one, but truncates the path to the last 4 elements. It's rather useful for other OSes, as well.

function exitstatus {
 if [ "$?" -eq "0" ]
 then
	COLOR=32
 else
	COLOR=31
 fi
}

PROMPT_COMMAND=exitstatus

PS1='$(
 IFS="/"
 d=3
 p=($(echo "\w"))
 e=$((${#p[@]}-1))
 P="\w"
 if [ $d -lt $e ]; then
 b=$(($e-$d+1))
 P="${p[$((b++))]}"
 for ((;$e-$b+1; b++)); do
 P="$P/${p[$b]}"
 done
 fi
 echo -n "\[\e[01;$COLOR;40m\]\u@\h\[\e[39m\]:\[\e[01;34m\]$P \[\e[0m\e]0;$P\$\a\]\$ "
 )'

While you're setting up bashrc and profile, you likely also want to setup $EDITOR, and the usual ll and la aliases (to ls --color).

Terminal emulator

The default setup uses Windows' DOS shell window to run bash. This gets annoyingvery quickly : it is not resizeable and has a lot of other bugs. I tried Console2 for a while but wasn't too happy with it either. The MinGW-provided rxvt seems to work fine. MinTTY looks interesting, but I didn't notice it before I was done with rxvt. Maybe next time...

Anyway, the default settings for rxvt are not too nice. I did some changes to make it a bit nicer and more useful. The first step is to open MSYS.BAT and replace the rxvt start command (start %WD%rxvt ...) with this:

set HOME=/home/USER
start %WD%rxvt -backspacekey ^H -sl 2500 -fn "Lucida Console-11" -fb "Lucida Console-11" -sr -geometry 132x50 -e /bin/sh --login -i

The HOME variable is set so rxvt can find .Xdefaults, and I also changed the font, increased the window size, and removed some color-related options.

Next step is to add a .Xdefaults file in the aformementionned HOME directory. There we'll setup the colors to look a bit nicer. Notice I used the same font for bold and normal text (rxvt bold rendering looks bad). So I set up different colors for bold and non-bold, so I can see all the 16 colors (rxvt could support up to 256, but this is not compiled in the mingw version). Here's my colorscheme.

Rxvt*color0: black
Rxvt*color1: orangered
Rxvt*color2: forestgreen
Rxvt*color3: gold
Rxvt*color4: dodgerblue4
Rxvt*color5: indigo
Rxvt*color6: cyan4
Rxvt*color7: azure3
Rxvt*color8: darkgrey
Rxvt*color9: crimson
Rxvt*color10: darkolivegreen1
Rxvt*color11: darkorange
Rxvt*color12: dodgerblue
Rxvt*color13: deeppink
Rxvt*color14: aquamarine
Rxvt*color15: white
Rxvt*background:gray7
Rxvt*foreground:aliceblue

More apps

Now install vim and svn (tortoiseSVN provides svn command-line client as an option in the installer), add them to bash path, and you're ready to go.

A little annoyance left : when started from bash, vim will read config in /home/user. When started from anywhere else, it will read in document and settings/user instead. So you have to copy your vimrc and vimfiles in both places.

Prompt Bash

Posted by pulkomandy on Sun Jul 17 16:50:09 2011  •  Comments (0)  • 

This bash prompt shows up in red when the last command failed ; green if everything is fine. It also sets xterm window title to the current directory. It displays a classical user@host$ prmpt, other than that. Put this in your bashrc file to enjoy it.

#fonction excute avant chaque affichage du prompt
function exitstatus {
        #rcupre la sortie de la dernire commande
 if [ "$?" -eq "0" ]
 then
        # 32 : vert
     PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
 else
        # 31 : rouge
     PS1='${debian_chroot:+($debian_chroot)}\[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
 fi
    # Ajoute le changement de titre des fentres xterm
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\W\$\a\]$PS1"
}

PROMPT_COMMAND=exitstatus

A variant for mksh is also available (with default/red colors, but it also prints the error code!). Put this in your mkshrc file.

function precmd {
	typeset e=$?

	(( e )) && print -n "\x1B[31m$e|"
}
PS1='
$(precmd)${USER:=$(ulimit -c 0;id -un 2>&-||print \?)}@${HOSTNAME%%.*}:$(
	typeset d=${PWD:-?} n p=~; [[ $p = ?(*/) ]] || d=${d/#$p/~}
	(( ${#d} > (n = (COLUMNS/3 < 7 ? 7 : COLUMNS/3)) )) && {
	d=${d:(-n)}; p=...; } || p=; print -nr -- "$p$d") '"$PS1 "

Trac subcomponents

Posted by pulkomandy on Thu Jul 14 16:50:15 2011  •  Comments (0)  • 

Just a little note, I set up a repository for APlayer and wanted to use subcomponents for issue reporting. This was a feature I used for years in Haiku bugtracker. It turned out to be a customization from the Haiku project. You can grab it there, along with other useful Trac mods.

Recuperer un fichier efface

Posted by pulkomandy on Tue Aug 4 19:07:12 2009  •  Comments (1)  • 

Une fausse manipulation peut arriver tout le monde (surtout moi)... Voici l'astuce secrte que j'utilise pour rcuprer un fichier effac par erreur. Elle a ses limites mais elle m'a dj rendu quelques services.

grep -aC 1000 "morceau de contenu du fichier" /dev/hda2 > /mnt/autrepart/dump

Comment a marche : grep va lire le contenu complet de la partition o se trouve le fichier effac (ici hda2), filtrer ce bazar et retrouver le morceau que vous lui spcifiez, pour chaque occurence trouve, il va l'enregistrer dans le fichier dump, avec les 1000 lignes prcdentes, et les 1000 suivantes. Il ne vous reste plus qu' rcuprer les morceaux de votre fichier dans ce dump...

Cette mthode est limite : d'abord a marche mal avec les fichiers binaires. En plus, a prend beaucoup de temps et il faut plein de place pour stocker le fichier dump. Il faut aussi se souvenir d'un morceau caractristique de votre fichier, ce qui n'est pas toujours vident. Mais, c'est dj mieux que rien. Pensez quand mme aux sauvegardes...

FluxBB et Gravatar

Posted by pulkomandy on Sun Jun 28 00:58:17 2009  •  Comments (1)  • 

gravatar.com est un site qui offre un service global de stockage d'avatars. On s'inscrit une fois, on uploade un avatar, et on peut l'utiliser pour tous les sites qui supportent le systme. Je suis administrateur d'un forum fluxbb et j'ai dcid de mettre a en place plutt que de laisser les utilisateurs remplir mon serveur avec leurs avatars. a a t plutt simple a faire:

gravatar.com is a website allowing his users to register, upload their favorite avatar once, and then use it everywhere. I've added support for it to a fluxbb forum. The hack was pretty simple:

(code original de fluxbb dans view_post.php) (original code in view_post.php)

  if ($pun_config['o_avatars'] == '1' && $cur_post['use_avatar'] == '1' && $pun_user['show_avatars'] != '0')
  {
   if ($img_size = @getimagesize($pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.gif'))
    $user_avatar = '<img src="'.$pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.gif" '.$img_size[3].' alt="" />';
   else if ($img_size = @getimagesize($pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.jpg'))
    $user_avatar = '<img src="'.$pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.jpg" '.$img_size[3].' alt="" />';
   else if ($img_size = @getimagesize($pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.png'))
    $user_avatar = '<img src="'.$pun_config['o_avatars_dir'].'/'.$cur_post['poster_id'].'.png" '.$img_size[3].' alt="" />';
  }
  else
   $user_avatar = '';

(a remplacer par) (replace with)

  $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5( strtolower($cur_post['email']) ).
//  "&default=".urlencode("http://une_belle_image").
  "&size=60";

  $user_avatar = '< img src="'.$grav_url.'">';

Le seul problme est que a oblige tous vos utilisateurs a utilise gravatar pour leur avatar, il n'est plus possible de l'uploader chez vous ou de le faire venir d'un autre site. Mais vous saurez surement trouver une solution plus propre pour faire a :)

The only drawback is that it enforces your users to upload their avatars to gravatar. They can't use another website or your own server. But i'm sure you can find a proper way to do it if you want :)

Convertir un script en HTML avec vim

Posted by pulkomandy on Fri Jun 26 22:17:31 2009  •  Comments (2)  • 

Une petite astuce qui permet de gagner du temps pour un site comme celui ci.

Plutt que de parser mes pages chaque affichage pour convertir les scripts et mettre des couleurs dedans, viter les problmes de mise en page lors de l'utilisation de < ou de &, j'utilise vim pour mettre mes scripts en couleur.

Il suffit d'utiliser la commande :TOhtml de vim qui s'occupe de tout. Ne reste plus qu' enlever les en-ttes html gnrs automatiquement par vim et copier le rsultat dans un article. Ma feuille de style contient les classes utilises et je peux choisir les couleurs facilement.

Script d'upload rapide en ftp

Posted by pulkomandy on Fri Jun 26 22:14:05 2009  •  Comments (0)  • 

Ce script vous permet d'envoyer facilement des fichiers sur un serveur depuis bash. Je l'utilise pour partager rapidement des fichiers depuis mon pc personnel directement sur mon serveur. adapter pour votre serveur, login, mot de passe et dossier de destination, bien sr...

#!/bin/sh
for i in "$@"
do
        if [ -f "$i" ]
        then
                HOST='serveur.com'
                USER='moi'
                PASSWD='mot_de_passe'
                FILE="\"$i\""
                ftp -n $HOST <<END_SCRIPT
                quote USER $USER
                quote PASS $PASSWD
                cd /ftp_upload
                put $FILE
                chmod 644 $FILE
END_SCRIPT
        else
                echo "$i is not a file !"
        fi
done

Configuration d'un serveur Debian

Posted by pulkomandy on Fri Jun 26 17:13:53 2009  •  Comments (1)  • 

Dans cet article, je vais dtailler un peu la configuration de ce serveur. Le but tait d'utiliser une machine peu puissante, mais peu bruyante et consommant peu d'lectricit. Je considre que ce n'est pas termin, donc, faites moi part de vos ides et de vos astuces pour l'amliorer.

Bien configurer le BIOS

Tout commence par l. J'ai dsactiv dans le BIOS tous les priphriques inutiles. Cela permet d'conomiser un peu d'lectricit grce la gestion ACPI, et a permet aussi d'viter de charger des modules noyau inutiles, donc on rcupre un peu de RAM. On enlve donc les lecteurs de disquettes et de CDrom (les alimentations sont dbranches), mais aussi les port sries et parallle.

D'autre part, le mode de gestion d'nergie ACPI dans le bios est "conomie maximale". Le processeur tourne lentement et chauffe moins, le disque dur est mis en veille au bout de 2 minutes

On gagne: de la mmoire et de l'lectricit

On perd: la posibilit de brancher un terminal VT100 et de dmarrer sur une disquette. Rien d'utile. On perd un peu en temps de rponse avec le disque dur en veille.

Les rglages de Debian

Il est galement importnat de bien configurer Debian. Les deux modifications que j'ai fait sont le dplacement de /var/log et de /tmp dans des ramdisks afin d'viter des accs inutiles au disque dur, et la desactivation de getty dans /etc/inittab. En effet getty occupe 6 fois 500Ko, et la mmoire vive est prcieuse.

La mmoire vive libre est utilise par Linux comme cache disque. Mon systme occupe moins de 16Mo de mmoire, il reste donc beaucoup de place pour ce cache. Cela permet d'avoir la plupart des pages de mon site dedans, ce qui fait qu'il est trs rare que le disque dur soit rveill lorsqu'un visiteur vient sur le site.

J'ai galement mont tous mes disques avec l'option noatime, ce qui vite d'avoir faire une criture sur le disque chaque lecture qui pourrait rester dans le cache.

On gagne: De la mmoire et du silence

On perd: La possibilit de brancher un cran sur la carte vga et un clavier ps/2 pour accder un prompt. Pensez configurer openssh avant.

Les logiciels

lighttpd pour le web, vsftpd pour le ftp et openssh. On vite Apache et proftpd qui sont beaucoup trop gros sans apporter grand chose d'utile.

La gestion des pages est faite l'aide de scripts perl mais sans base de donnes SQL. J'utilise des fichiers et des dossiers, les utilisateurs UNIX et les dates de modifications. a allge beaucoup le serveur et a ne limite pas forcment les possibilits.

On gagne: De la mmoire et de la ractivit, et de la scurit (pas d'injections SQL)

On perd: Le confort de php/MySQL, un peu de souplesse

Trucs qui restent faire

  • Recompiler le noyau en enlevant tous les trucs inutiles devrait permettre d'allger encore le systme.
  • Configurer lighttpd pour utiliser perl en fastcgi pour gagner encore en vitesse de rponse.
  • Mettre en place une authentification http utilisant directement les utilisateurs unix pour viter d'avoir grer deux listes de logins.