FlatCAMApp.py 286 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. from PyQt5.QtCore import QSettings
  23. import time # Just used for debugging. Double check before removing.
  24. import urllib.request, urllib.parse, urllib.error
  25. import webbrowser
  26. from contextlib import contextmanager
  27. from xml.dom.minidom import parseString as parse_xml_string
  28. from copy import copy,deepcopy
  29. import numpy as np
  30. from datetime import datetime
  31. import gc
  32. ########################################
  33. ## Imports part of FlatCAM ##
  34. ########################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from PlotCanvas import *
  38. from FlatCAMGUI import *
  39. from FlatCAMCommon import LoudDict
  40. from FlatCAMPostProc import load_postprocessors
  41. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. from multiprocessing import Pool
  49. import tclCommands
  50. # from ParseFont import *
  51. ########################################
  52. ## App ##
  53. ########################################
  54. class App(QtCore.QObject):
  55. """
  56. The main application class. The constructor starts the GUI.
  57. """
  58. # Get Cmd Line Options
  59. cmd_line_shellfile = ''
  60. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  61. try:
  62. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  63. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  64. except getopt.GetoptError:
  65. print(cmd_line_help)
  66. sys.exit(2)
  67. for opt, arg in cmd_line_options:
  68. if opt == '-h':
  69. print(cmd_line_help)
  70. sys.exit()
  71. elif opt == '--shellfile':
  72. cmd_line_shellfile = arg
  73. # Logging ##
  74. log = logging.getLogger('base')
  75. log.setLevel(logging.DEBUG)
  76. # log.setLevel(logging.WARNING)
  77. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  78. handler = logging.StreamHandler()
  79. handler.setFormatter(formatter)
  80. log.addHandler(handler)
  81. # Version
  82. version = 8.909
  83. version_date = "2019/02/15"
  84. beta = True
  85. # current date now
  86. date = str(datetime.today()).rpartition(' ')[0]
  87. # URL for update checks and statistics
  88. version_url = "http://flatcam.org/version"
  89. # App URL
  90. app_url = "http://flatcam.org"
  91. # Manual URL
  92. manual_url = "http://flatcam.org/manual/index.html"
  93. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  94. should_we_quit = True
  95. ##################
  96. ## Signals ##
  97. ##################
  98. # Inform the user
  99. # Handled by:
  100. # * App.info() --> Print on the status bar
  101. inform = QtCore.pyqtSignal(str)
  102. # General purpose background task
  103. worker_task = QtCore.pyqtSignal(dict)
  104. # File opened
  105. # Handled by:
  106. # * register_folder()
  107. # * register_recent()
  108. # Note: Setting the parameters to unicode does not seem
  109. # to have an effect. Then are received as Qstring
  110. # anyway.
  111. # File type and filename
  112. file_opened = QtCore.pyqtSignal(str, str)
  113. # File type and filename
  114. file_saved = QtCore.pyqtSignal(str, str)
  115. # Percentage of progress
  116. progress = QtCore.pyqtSignal(int)
  117. plots_updated = QtCore.pyqtSignal()
  118. # Emitted by new_object() and passes the new object as argument, plot flag.
  119. # on_object_created() adds the object to the collection, plots on appropriate flag
  120. # and emits new_object_available.
  121. object_created = QtCore.pyqtSignal(object, bool, bool)
  122. # Emitted when a object has been changed (like scaled, mirrored)
  123. object_changed = QtCore.pyqtSignal(object)
  124. # Emitted after object has been plotted.
  125. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  126. object_plotted = QtCore.pyqtSignal(object)
  127. # Emitted when a new object has been added to the collection
  128. # and is ready to be used.
  129. new_object_available = QtCore.pyqtSignal(object)
  130. message = QtCore.pyqtSignal(str, str, str)
  131. # Emmited when shell command is finished(one command only)
  132. shell_command_finished = QtCore.pyqtSignal(object)
  133. # Emitted when multiprocess pool has been recreated
  134. pool_recreated = QtCore.pyqtSignal(object)
  135. # Emitted when an unhandled exception happens
  136. # in the worker task.
  137. thread_exception = QtCore.pyqtSignal(object)
  138. def __init__(self, user_defaults=True, post_gui=None):
  139. """
  140. Starts the application.
  141. :return: app
  142. :rtype: App
  143. """
  144. App.log.info("FlatCAM Starting...")
  145. ###################
  146. ### OS-specific ###
  147. ###################
  148. # Folder for user settings.
  149. if sys.platform == 'win32':
  150. from win32com.shell import shell, shellcon
  151. if platform.architecture()[0] == '32bit':
  152. App.log.debug("Win32!")
  153. else:
  154. App.log.debug("Win64!")
  155. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  156. '\FlatCAM'
  157. self.os = 'windows'
  158. else: # Linux/Unix/MacOS
  159. self.data_path = os.path.expanduser('~') + \
  160. '/.FlatCAM'
  161. self.os = 'unix'
  162. ###############################
  163. ### Setup folders and files ###
  164. ###############################
  165. if not os.path.exists(self.data_path):
  166. os.makedirs(self.data_path)
  167. App.log.debug('Created data folder: ' + self.data_path)
  168. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  169. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  170. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  171. if not os.path.exists(self.postprocessorpaths):
  172. os.makedirs(self.postprocessorpaths)
  173. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  174. # create current_defaults.FlatConfig file if there is none
  175. try:
  176. f = open(self.data_path + '/current_defaults.FlatConfig')
  177. f.close()
  178. except IOError:
  179. App.log.debug('Creating empty current_defaults.FlatConfig')
  180. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  181. json.dump({}, f)
  182. f.close()
  183. # create factory_defaults.FlatConfig file if there is none
  184. try:
  185. f = open(self.data_path + '/factory_defaults.FlatConfig')
  186. f.close()
  187. except IOError:
  188. App.log.debug('Creating empty factory_defaults.FlatConfig')
  189. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  190. json.dump({}, f)
  191. f.close()
  192. try:
  193. f = open(self.data_path + '/recent.json')
  194. f.close()
  195. except IOError:
  196. App.log.debug('Creating empty recent.json')
  197. f = open(self.data_path + '/recent.json', 'w')
  198. json.dump([], f)
  199. f.close()
  200. # Application directory. CHDIR to it. Otherwise, trying to load
  201. # GUI icons will fail as their path is relative.
  202. # This will fail under cx_freeze ...
  203. self.app_home = os.path.dirname(os.path.realpath(__file__))
  204. App.log.debug("Application path is " + self.app_home)
  205. App.log.debug("Started in " + os.getcwd())
  206. # cx_freeze workaround
  207. if os.path.isfile(self.app_home):
  208. self.app_home = os.path.dirname(self.app_home)
  209. os.chdir(self.app_home)
  210. # Create multiprocessing pool
  211. self.pool = Pool()
  212. # variable to store mouse coordinates
  213. self.mouse = [0, 0]
  214. ####################
  215. ## Initialize GUI ##
  216. ####################
  217. # FlatCAM colors used in plotting
  218. self.FC_light_green = '#BBF268BF'
  219. self.FC_dark_green = '#006E20BF'
  220. self.FC_light_blue = '#a5a5ffbf'
  221. self.FC_dark_blue = '#0000ffbf'
  222. QtCore.QObject.__init__(self)
  223. self.ui = FlatCAMGUI(self.version, self.beta, self)
  224. # self.connect(self.ui,
  225. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  226. # self.save_geometry) PyQt4
  227. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  228. self.ui.final_save.connect(self.final_save)
  229. ##############
  230. #### Data ####
  231. ##############
  232. self.recent = []
  233. self.clipboard = QtWidgets.QApplication.clipboard()
  234. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  235. self.project_filename = None
  236. self.toggle_units_ignore = False
  237. # self.defaults_form = PreferencesUI()
  238. self.general_defaults_form = GeneralPreferencesUI()
  239. self.gerber_defaults_form = GerberPreferencesUI()
  240. self.excellon_defaults_form = ExcellonPreferencesUI()
  241. self.geometry_defaults_form = GeometryPreferencesUI()
  242. self.cncjob_defaults_form = CNCJobPreferencesUI()
  243. self.tools_defaults_form = ToolsPreferencesUI()
  244. # when adding entries here read the comments in the method found bellow named:
  245. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  246. self.defaults_form_fields = {
  247. "units": self.general_defaults_form.general_app_group.units_radio,
  248. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  249. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  250. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  251. "global_project_at_startup": self.general_defaults_form.general_app_group.project_startup_cb,
  252. "global_project_autohide": self.general_defaults_form.general_app_group.project_autohide_cb,
  253. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  254. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  255. "global_snap_max": self.general_defaults_form.general_gui_group.snap_max_dist_entry,
  256. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  257. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  258. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  259. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  260. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  261. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  262. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  263. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  264. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  265. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  266. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  267. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  268. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  269. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  270. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  271. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  272. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  273. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  274. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  275. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  276. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  277. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  278. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  279. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  280. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  281. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  282. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  283. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  284. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  285. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  286. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  287. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  288. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  289. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  290. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  291. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  292. "excellon_offset": self.excellon_defaults_form.excellon_gen_group.offset_entry,
  293. "excellon_toolchangexy": self.excellon_defaults_form.excellon_gen_group.toolchangexy_entry,
  294. "excellon_startz": self.excellon_defaults_form.excellon_gen_group.estartz_entry,
  295. "excellon_endz": self.excellon_defaults_form.excellon_gen_group.eendz_entry,
  296. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_gen_group.feedrate_rapid_entry,
  297. "excellon_z_pdepth": self.excellon_defaults_form.excellon_gen_group.pdepth_entry,
  298. "excellon_feedrate_probe": self.excellon_defaults_form.excellon_gen_group.feedrate_probe_entry,
  299. "excellon_f_plunge": self.excellon_defaults_form.excellon_gen_group.fplunge_cb,
  300. "excellon_f_retract": self.excellon_defaults_form.excellon_gen_group.fretract_cb,
  301. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  302. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  303. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  304. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  305. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  306. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  307. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  308. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  309. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  310. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  311. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  312. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  313. "excellon_exp_units": self.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  314. "excellon_exp_format": self.excellon_defaults_form.excellon_exp_group.format_radio,
  315. "excellon_exp_integer": self.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  316. "excellon_exp_decimals": self.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  317. "excellon_exp_zeros": self.excellon_defaults_form.excellon_exp_group.zeros_radio,
  318. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  319. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  320. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  321. "geometry_segx": self.geometry_defaults_form.geometry_gen_group.segx_entry,
  322. "geometry_segy": self.geometry_defaults_form.geometry_gen_group.segy_entry,
  323. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_gen_group.cncfeedrate_rapid_entry,
  324. "geometry_feedrate_probe": self.geometry_defaults_form.geometry_gen_group.feedrate_probe_entry,
  325. "geometry_z_pdepth": self.geometry_defaults_form.geometry_gen_group.pdepth_entry,
  326. "geometry_f_plunge": self.geometry_defaults_form.geometry_gen_group.fplunge_cb,
  327. "geometry_toolchangexy": self.geometry_defaults_form.geometry_gen_group.toolchangexy_entry,
  328. "geometry_startz": self.geometry_defaults_form.geometry_gen_group.gstartz_entry,
  329. "geometry_endz": self.geometry_defaults_form.geometry_gen_group.gendz_entry,
  330. "geometry_extracut": self.geometry_defaults_form.geometry_gen_group.extracut_cb,
  331. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  332. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  333. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  334. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  335. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  336. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  337. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  338. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  339. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  340. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  341. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  342. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  343. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  344. "cncjob_plot_kind": self.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  345. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  346. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  347. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  348. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  349. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  350. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  351. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  352. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  353. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  354. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  355. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  356. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  357. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  358. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  359. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  360. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  361. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  362. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  363. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  364. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  365. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  366. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  367. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  368. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  369. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  370. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  371. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  372. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  373. "tools_film_type": self.tools_defaults_form.tools_film_group.film_type_radio,
  374. "tools_film_boundary": self.tools_defaults_form.tools_film_group.film_boundary_entry,
  375. "tools_film_scale": self.tools_defaults_form.tools_film_group.film_scale_entry,
  376. "tools_panelize_spacing_columns": self.tools_defaults_form.tools_panelize_group.pspacing_columns,
  377. "tools_panelize_spacing_rows": self.tools_defaults_form.tools_panelize_group.pspacing_rows,
  378. "tools_panelize_columns": self.tools_defaults_form.tools_panelize_group.pcolumns,
  379. "tools_panelize_rows": self.tools_defaults_form.tools_panelize_group.prows,
  380. "tools_panelize_constrain": self.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  381. "tools_panelize_constrainx": self.tools_defaults_form.tools_panelize_group.px_width_entry,
  382. "tools_panelize_constrainy": self.tools_defaults_form.tools_panelize_group.py_height_entry,
  383. "tools_calc_vshape_tip_dia": self.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  384. "tools_calc_vshape_tip_angle": self.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  385. "tools_calc_vshape_cut_z": self.tools_defaults_form.tools_calculators_group.cut_z_entry,
  386. "tools_calc_electro_length": self.tools_defaults_form.tools_calculators_group.pcblength_entry,
  387. "tools_calc_electro_width": self.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  388. "tools_calc_electro_cdensity": self.tools_defaults_form.tools_calculators_group.cdensity_entry,
  389. "tools_calc_electro_growth": self.tools_defaults_form.tools_calculators_group.growth_entry
  390. }
  391. # loads postprocessors
  392. self.postprocessors = load_postprocessors(self)
  393. for name in list(self.postprocessors.keys()):
  394. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  395. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  396. if name == 'hpgl':
  397. continue
  398. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  399. self.defaults = LoudDict()
  400. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  401. self.defaults.update({
  402. "global_serial": 0,
  403. "global_stats": {},
  404. "units": "IN",
  405. "global_version_check": True,
  406. "global_send_stats": True,
  407. "global_project_at_startup": False,
  408. "global_project_autohide": True,
  409. "global_gridx": 1.0,
  410. "global_gridy": 1.0,
  411. "global_snap_max": 0.05,
  412. "global_grid_context_menu": {
  413. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  414. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  415. },
  416. "global_plot_fill": '#BBF268BF',
  417. "global_plot_line": '#006E20BF',
  418. "global_sel_fill": '#a5a5ffbf',
  419. "global_sel_line": '#0000ffbf',
  420. "global_alt_sel_fill": '#BBF268BF',
  421. "global_alt_sel_line": '#006E20BF',
  422. "global_draw_color": '#FF0000',
  423. "global_sel_draw_color": '#0000FF',
  424. "global_pan_button": '2',
  425. "global_mselect_key": 'Control',
  426. # "global_pan_with_space_key": False,
  427. "global_workspace": False,
  428. "global_workspaceT": "A4P",
  429. "global_toolbar_view": 127,
  430. "global_background_timeout": 300000, # Default value is 5 minutes
  431. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  432. # (python trace only for unknown errors),
  433. # 1 = show trace(show trace allways),
  434. # 2 = (For the future).
  435. # Persistence
  436. "global_last_folder": None,
  437. "global_last_save_folder": None,
  438. # Default window geometry
  439. "global_def_win_x": 100,
  440. "global_def_win_y": 100,
  441. "global_def_win_w": 1024,
  442. "global_def_win_h": 650,
  443. # Constants...
  444. "global_defaults_save_period_ms": 20000, # Time between default saves.
  445. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  446. "global_shell_at_startup": False, # Show the shell at startup.
  447. "global_recent_limit": 10, # Max. items in recent list.
  448. "fit_key": 'V',
  449. "zoom_out_key": '-',
  450. "zoom_in_key": '=',
  451. "grid_toggle_key": 'G',
  452. "zoom_ratio": 1.5,
  453. "global_point_clipboard_format": "(%.4f, %.4f)",
  454. "global_zdownrate": None,
  455. "gerber_plot": True,
  456. "gerber_solid": True,
  457. "gerber_multicolored": False,
  458. "gerber_isotooldia": 0.016,
  459. "gerber_isopasses": 1,
  460. "gerber_isooverlap": 0.15,
  461. "gerber_combine_passes": False,
  462. "gerber_milling_type": "cl",
  463. "gerber_noncoppermargin": 0.1,
  464. "gerber_noncopperrounded": False,
  465. "gerber_bboxmargin": 0.1,
  466. "gerber_bboxrounded": False,
  467. "gerber_circle_steps": 64,
  468. "gerber_use_buffer_for_union": True,
  469. "excellon_plot": True,
  470. "excellon_solid": True,
  471. "excellon_format_upper_in": 2,
  472. "excellon_format_lower_in": 4,
  473. "excellon_format_upper_mm": 3,
  474. "excellon_format_lower_mm": 3,
  475. "excellon_zeros": "L",
  476. "excellon_units": "INCH",
  477. "excellon_optimization_type": 'B',
  478. "excellon_search_time": 3,
  479. "excellon_drillz": -0.1,
  480. "excellon_travelz": 0.1,
  481. "excellon_feedrate": 3.0,
  482. "excellon_feedrate_rapid": 3.0,
  483. "excellon_feedrate_probe": 3.0,
  484. "excellon_spindlespeed": None,
  485. "excellon_dwell": False,
  486. "excellon_dwelltime": 1,
  487. "excellon_toolchange": False,
  488. "excellon_toolchangez": 1.0,
  489. "excellon_toolchangexy": "0.0, 0.0",
  490. "excellon_tooldia": 0.016,
  491. "excellon_offset": 0.0,
  492. "excellon_slot_tooldia": 0.016,
  493. "excellon_startz": None,
  494. "excellon_endz": 2.0,
  495. "excellon_ppname_e": 'default',
  496. "excellon_z_pdepth": -0.02,
  497. "excellon_f_plunge": False,
  498. "excellon_f_retract": False,
  499. "excellon_gcode_type": "drills",
  500. "excellon_exp_units": 'INCH',
  501. "excellon_exp_format": 'ndec',
  502. "excellon_exp_integer": 2,
  503. "excellon_exp_decimals": 4,
  504. "excellon_exp_zeros": 'LZ',
  505. "geometry_plot": True,
  506. "geometry_segx": 0.0,
  507. "geometry_segy": 0.0,
  508. "geometry_cutz": -0.002,
  509. "geometry_travelz": 0.1,
  510. "geometry_toolchange": False,
  511. "geometry_toolchangez": 1.0,
  512. "geometry_toolchangexy": "0.0, 0.0",
  513. "geometry_startz": None,
  514. "geometry_endz": 2.0,
  515. "geometry_feedrate": 3.0,
  516. "geometry_feedrate_z": 3.0,
  517. "geometry_feedrate_rapid": 3.0,
  518. "geometry_feedrate_probe": 3.0,
  519. "geometry_cnctooldia": 0.016,
  520. "geometry_spindlespeed": None,
  521. "geometry_dwell": False,
  522. "geometry_dwelltime": 1,
  523. "geometry_ppname_g": 'default',
  524. "geometry_z_pdepth": -0.02,
  525. "geometry_f_plunge": False,
  526. "geometry_depthperpass": 0.002,
  527. "geometry_multidepth": False,
  528. "geometry_extracut": False,
  529. "geometry_circle_steps": 64,
  530. "cncjob_plot": True,
  531. "cncjob_plot_kind": 'all',
  532. "cncjob_tooldia": 0.0393701,
  533. "cncjob_coords_decimals": 4,
  534. "cncjob_fr_decimals": 2,
  535. "cncjob_prepend": "",
  536. "cncjob_append": "",
  537. "cncjob_steps_per_circle": 64,
  538. "tools_ncctools": "1.0, 0.5",
  539. "tools_nccoverlap": 0.4,
  540. "tools_nccmargin": 0.1,
  541. "tools_nccmethod": "seed",
  542. "tools_nccconnect": True,
  543. "tools_ncccontour": True,
  544. "tools_nccrest": False,
  545. "tools_cutouttooldia": 0.1,
  546. "tools_cutoutmargin": 0.1,
  547. "tools_cutoutgapsize": 0.15,
  548. "tools_gaps_rect": "4",
  549. "tools_gaps_ff": "8",
  550. "tools_painttooldia": 0.07,
  551. "tools_paintoverlap": 0.15,
  552. "tools_paintmargin": 0.0,
  553. "tools_paintmethod": "seed",
  554. "tools_selectmethod": "single",
  555. "tools_pathconnect": True,
  556. "tools_paintcontour": True,
  557. "tools_2sided_mirror_axis": "X",
  558. "tools_2sided_axis_loc": "point",
  559. "tools_2sided_drilldia": 1,
  560. "tools_film_type": 'neg',
  561. "tools_film_boundary": 1,
  562. "tools_film_scale": 0,
  563. "tools_panelize_spacing_columns": 0,
  564. "tools_panelize_spacing_rows": 0,
  565. "tools_panelize_columns": 1,
  566. "tools_panelize_rows": 1,
  567. "tools_panelize_constrain": False,
  568. "tools_panelize_constrainx": 0.0,
  569. "tools_panelize_constrainy": 0.0,
  570. "tools_calc_vshape_tip_dia": 0.007874,
  571. "tools_calc_vshape_tip_angle": 30,
  572. "tools_calc_vshape_cut_z": 0.000787,
  573. "tools_calc_electro_length": 10.0,
  574. "tools_calc_electro_width": 10.0,
  575. "tools_calc_electro_cdensity":13.0,
  576. "tools_calc_electro_growth": 10.0
  577. })
  578. ###############################
  579. ### Load defaults from file ###
  580. if user_defaults:
  581. self.load_defaults(filename='current_defaults')
  582. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  583. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  584. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  585. self.save_defaults(silent=True)
  586. self.propagate_defaults(silent=True)
  587. self.restore_main_win_geom()
  588. def auto_save_defaults():
  589. try:
  590. self.save_defaults(silent=True)
  591. self.propagate_defaults(silent=True)
  592. finally:
  593. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  594. # the following lines activates automatic defaults save
  595. # if user_defaults:
  596. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  597. # self.options_form = PreferencesUI()
  598. self.general_options_form = GeneralPreferencesUI()
  599. self.gerber_options_form = GerberPreferencesUI()
  600. self.excellon_options_form = ExcellonPreferencesUI()
  601. self.geometry_options_form = GeometryPreferencesUI()
  602. self.cncjob_options_form = CNCJobPreferencesUI()
  603. self.tools_options_form = ToolsPreferencesUI()
  604. self.options_form_fields = {
  605. "units": self.general_options_form.general_app_group.units_radio,
  606. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  607. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  608. "global_snap_max": self.general_options_form.general_gui_group.snap_max_dist_entry,
  609. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  610. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  611. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  612. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  613. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  614. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  615. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  616. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  617. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  618. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  619. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  620. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  621. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  622. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  623. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  624. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  625. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  626. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  627. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  628. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  629. "excellon_feedrate_rapid": self.excellon_options_form.excellon_gen_group.feedrate_rapid_entry,
  630. "excellon_toolchangexy": self.excellon_options_form.excellon_gen_group.toolchangexy_entry,
  631. "excellon_f_plunge": self.excellon_options_form.excellon_gen_group.fplunge_cb,
  632. "excellon_startz": self.excellon_options_form.excellon_gen_group.estartz_entry,
  633. "excellon_endz": self.excellon_options_form.excellon_gen_group.eendz_entry,
  634. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  635. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  636. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  637. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  638. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  639. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  640. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  641. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  642. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  643. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  644. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  645. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  646. "geometry_segx": self.geometry_options_form.geometry_gen_group.segx_entry,
  647. "geometry_segy": self.geometry_options_form.geometry_gen_group.segy_entry,
  648. "geometry_feedrate_rapid": self.geometry_options_form.geometry_gen_group.cncfeedrate_rapid_entry,
  649. "geometry_f_plunge": self.geometry_options_form.geometry_gen_group.fplunge_cb,
  650. "geometry_toolchangexy": self.geometry_options_form.geometry_gen_group.toolchangexy_entry,
  651. "geometry_startz": self.geometry_options_form.geometry_gen_group.gstartz_entry,
  652. "geometry_endz": self.geometry_options_form.geometry_gen_group.gendz_entry,
  653. "geometry_extracut": self.geometry_options_form.geometry_gen_group.extracut_cb,
  654. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  655. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  656. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  657. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  658. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  659. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  660. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  661. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  662. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  663. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  664. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  665. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  666. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  667. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  668. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  669. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  670. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  671. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  672. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  673. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  674. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  675. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  676. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  677. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  678. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  679. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  680. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  681. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  682. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  683. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  684. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  685. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  686. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  687. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry,
  688. "tools_film_type": self.tools_options_form.tools_film_group.film_type_radio,
  689. "tools_film_boundary": self.tools_options_form.tools_film_group.film_boundary_entry,
  690. "tools_film_scale": self.tools_options_form.tools_film_group.film_scale_entry,
  691. "tools_panelize_spacing_columns": self.tools_options_form.tools_panelize_group.pspacing_columns,
  692. "tools_panelize_spacing_rows": self.tools_options_form.tools_panelize_group.pspacing_rows,
  693. "tools_panelize_columns": self.tools_options_form.tools_panelize_group.pcolumns,
  694. "tools_panelize_rows": self.tools_options_form.tools_panelize_group.prows,
  695. "tools_panelize_constrain": self.tools_options_form.tools_panelize_group.pconstrain_cb,
  696. "tools_panelize_constrainx": self.tools_options_form.tools_panelize_group.px_width_entry,
  697. "tools_panelize_constrainy": self.tools_options_form.tools_panelize_group.py_height_entry
  698. }
  699. for name in list(self.postprocessors.keys()):
  700. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  701. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  702. self.options = LoudDict()
  703. self.options.set_change_callback(self.on_options_dict_change)
  704. self.options.update({
  705. "units": "IN",
  706. "global_gridx": 1.0,
  707. "global_gridy": 1.0,
  708. "global_snap_max": 0.05,
  709. "global_background_timeout": 300000, # Default value is 5 minutes
  710. "global_verbose_error_level": 0, # Shell verbosity:
  711. # 0 = default(python trace only for unknown errors),
  712. # 1 = show trace(show trace allways), 2 = (For the future).
  713. "gerber_plot": True,
  714. "gerber_solid": True,
  715. "gerber_multicolored": False,
  716. "gerber_isotooldia": 0.016,
  717. "gerber_isopasses": 1,
  718. "gerber_isooverlap": 0.15,
  719. "gerber_combine_passes": True,
  720. "gerber_noncoppermargin": 0.0,
  721. "gerber_noncopperrounded": False,
  722. "gerber_bboxmargin": 0.0,
  723. "gerber_bboxrounded": False,
  724. "excellon_plot": True,
  725. "excellon_solid": False,
  726. "excellon_format_upper_in": 2,
  727. "excellon_format_lower_in": 4,
  728. "excellon_format_upper_mm": 3,
  729. "excellon_format_lower_mm": 3,
  730. "excellon_units": 'INCH',
  731. "excellon_optimization_type": 'B',
  732. "excellon_search_time": 3,
  733. "excellon_zeros": "L",
  734. "excellon_drillz": -0.1,
  735. "excellon_travelz": 0.1,
  736. "excellon_feedrate": 3.0,
  737. "excellon_feedrate_rapid": 3.0,
  738. "excellon_spindlespeed": None,
  739. "excellon_dwell": True,
  740. "excellon_dwelltime": 1000,
  741. "excellon_toolchange": False,
  742. "excellon_toolchangez": 1.0,
  743. "excellon_toolchangexy": "0.0, 0.0",
  744. "excellon_tooldia": 0.016,
  745. "excellon_ppname_e": 'default',
  746. "excellon_f_plunge": False,
  747. "excellon_startz": None,
  748. "excellon_endz": 2.0,
  749. "geometry_plot": True,
  750. "geometry_segx": 0.0,
  751. "geometry_segy": 0.0,
  752. "geometry_cutz": -0.002,
  753. "geometry_travelz": 0.1,
  754. "geometry_feedrate": 3.0,
  755. "geometry_feedrate_z": 3.0,
  756. "geometry_feedrate_rapid": 3.0,
  757. "geometry_spindlespeed": None,
  758. "geometry_dwell": True,
  759. "geometry_dwelltime": 1000,
  760. "geometry_cnctooldia": 0.016,
  761. "geometry_toolchange": False,
  762. "geometry_toolchangez": 2.0,
  763. "geometry_toolchangexy": "0.0, 0.0",
  764. "geometry_startz": None,
  765. "geometry_endz": 2.0,
  766. "geometry_ppname_g": "default",
  767. "geometry_f_plunge": False,
  768. "geometry_depthperpass": 0.002,
  769. "geometry_multidepth": False,
  770. "geometry_extracut": False,
  771. "cncjob_plot": True,
  772. "cncjob_tooldia": 0.016,
  773. "cncjob_prepend": "",
  774. "cncjob_append": "",
  775. "tools_ncctools": "1.0, 0.5",
  776. "tools_nccoverlap": 0.4,
  777. "tools_nccmargin": 1,
  778. "tools_cutouttooldia": 0.07,
  779. "tools_cutoutmargin": 0.1,
  780. "tools_cutoutgapsize": 0.15,
  781. "tools_gaps_rect": "4",
  782. "tools_gaps_ff": "8",
  783. "tools_painttooldia": 0.07,
  784. "tools_paintoverlap": 0.15,
  785. "tools_paintmargin": 0.0,
  786. "tools_paintmethod": "seed",
  787. "tools_selectmethod": "single",
  788. "tools_pathconnect": True,
  789. "tools_paintcontour": True,
  790. "tools_2sided_mirror_axis": "X",
  791. "tools_2sided_axis_loc": 'point',
  792. "tools_2sided_drilldia": 1,
  793. "tools_film_type": 'neg',
  794. "tools_film_boundary": 1,
  795. "tools_film_scale": 0,
  796. "tools_panelize_spacing_columns": 0,
  797. "tools_panelize_spacing_rows": 0,
  798. "tools_panelize_columns": 1,
  799. "tools_panelize_rows": 1,
  800. "tools_panelize_constrain": False,
  801. "tools_panelize_constrainx": 0.0,
  802. "tools_panelize_constrainy": 0.0
  803. })
  804. self.options.update(self.defaults) # Copy app defaults to project options
  805. self.gen_form = None
  806. self.ger_form = None
  807. self.exc_form = None
  808. self.geo_form = None
  809. self.cnc_form = None
  810. self.tools_form = None
  811. self.on_options_combo_change(0) # Will show the initial form
  812. ### Define OBJECT COLLECTION ###
  813. self.collection = ObjectCollection(self)
  814. self.ui.project_tab_layout.addWidget(self.collection.view)
  815. ###
  816. self.log.debug("Finished creating Object Collection.")
  817. ### Initialize the color box's color in Preferences -> Global -> Color
  818. # Init Plot Colors
  819. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  820. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  821. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  822. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  823. int(self.defaults['global_plot_fill'][7:9], 16))
  824. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  825. int(self.defaults['global_plot_fill'][7:9], 16))
  826. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  827. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  828. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  829. # Init Left-Right Selection colors
  830. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  831. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  832. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  833. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  834. int(self.defaults['global_sel_fill'][7:9], 16))
  835. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  836. int(self.defaults['global_sel_fill'][7:9], 16))
  837. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  838. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  839. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  840. # Init Right-Left Selection colors
  841. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  842. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  843. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  844. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  845. int(self.defaults['global_sel_fill'][7:9], 16))
  846. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  847. int(self.defaults['global_sel_fill'][7:9], 16))
  848. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  849. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  850. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  851. # Init Draw color and Selection Draw Color
  852. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  853. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  854. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  855. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  856. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  857. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  858. #### End of Data ####
  859. #### Plot Area ####
  860. start_plot_time = time.time() # debug
  861. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  862. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  863. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  864. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  865. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  866. # Keys over plot enabled
  867. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  868. self.ui.splitter.setStretchFactor(1, 2)
  869. # So it can receive key presses
  870. self.plotcanvas.vispy_canvas.native.setFocus()
  871. self.app_cursor = self.plotcanvas.new_cursor()
  872. self.app_cursor.enabled = False
  873. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  874. # depending on from where those tools are called different actions can be done
  875. self.call_source = 'app'
  876. end_plot_time = time.time()
  877. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  878. ### EDITOR section
  879. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  880. self.exc_editor = FlatCAMExcEditor(self)
  881. #### Adjust tabs width ####
  882. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  883. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  884. self.collection.view.setMinimumWidth(290)
  885. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  886. #### Worker ####
  887. self.workers = WorkerStack()
  888. self.worker_task.connect(self.workers.add_task)
  889. ### Signal handling ###
  890. ## Custom signals
  891. self.inform.connect(self.info)
  892. self.message.connect(self.message_dialog)
  893. self.progress.connect(self.set_progress_bar)
  894. self.object_created.connect(self.on_object_created)
  895. self.object_changed.connect(self.on_object_changed)
  896. self.object_plotted.connect(self.on_object_plotted)
  897. self.plots_updated.connect(self.on_plots_updated)
  898. self.file_opened.connect(self.register_recent)
  899. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  900. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  901. ## Standard signals
  902. # Menu
  903. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  904. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  905. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  906. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  907. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  908. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  909. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  910. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  911. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  912. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  913. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  914. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  915. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  916. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  917. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  918. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  919. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  920. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  921. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  922. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  923. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  924. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  925. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  926. self.ui.menueditedit.triggered.connect(self.object2editor)
  927. self.ui.menueditok.triggered.connect(self.editor2object)
  928. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  929. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  930. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  931. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  932. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  933. self.ui.menueditdelete.triggered.connect(self.on_delete)
  934. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  935. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  936. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  937. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  938. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  939. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  940. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  941. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  942. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  943. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  944. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  945. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  946. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  947. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  948. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  949. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  950. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  951. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  952. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  953. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  954. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  955. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  956. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  957. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  958. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  959. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  960. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  961. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  962. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  963. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  964. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  965. self.ui.menuhelp_about.triggered.connect(self.on_about)
  966. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  967. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  968. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  969. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  970. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  971. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  972. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  973. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  974. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  975. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  976. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  977. # Toolbar
  978. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  979. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  980. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  981. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  982. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  983. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  984. self.ui.replot_btn.triggered.connect(self.plot_all)
  985. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  986. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  987. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  988. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  989. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  990. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  991. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  992. self.ui.delete_btn.triggered.connect(self.on_delete)
  993. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  994. # Context Menu
  995. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  996. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  997. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  998. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  999. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1000. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1001. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1002. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1003. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1004. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1005. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1006. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1007. self.ui.clearplot.triggered.connect(self.clear_plots)
  1008. self.ui.replot.triggered.connect(self.plot_all)
  1009. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1010. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1011. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1012. self.ui.popmenu_save.triggered.connect(self.editor2object)
  1013. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1014. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1015. # Preferences Plot Area TAB
  1016. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1017. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1018. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1019. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1020. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1021. ###############################
  1022. ### GUI PREFERENCES SIGNALS ###
  1023. ###############################
  1024. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1025. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  1026. ###############################
  1027. ### GUI PREFERENCES SIGNALS ###
  1028. ###############################
  1029. # Setting plot colors signals
  1030. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1031. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1032. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1033. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1034. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1035. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1036. # Setting selection (left - right) colors signals
  1037. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1038. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1039. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1040. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1041. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1042. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1043. # Setting selection (right - left) colors signals
  1044. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1045. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1046. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1047. self.on_alt_sf_color_spinner)
  1048. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1049. self.on_alt_sf_color_slider)
  1050. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1051. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1052. # Setting Editor Draw colors signals
  1053. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1054. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1055. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1056. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1057. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1058. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1059. self.general_defaults_form.general_gui_group.layout_combo.activated.connect(self.on_layout)
  1060. # Modify G-CODE Plot Area TAB
  1061. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1062. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1063. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1064. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1065. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1066. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1067. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1068. # Object list
  1069. self.collection.view.activated.connect(self.on_row_activated)
  1070. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1071. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1072. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1073. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1074. self.on_excellon_defaults_button)
  1075. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1076. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1077. self.on_excellon_options_button)
  1078. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1079. self.tool_tab_locked = False
  1080. # decide if to show or hide the Notebook side of the screen at startup
  1081. if self.defaults["global_project_at_startup"] is True:
  1082. self.ui.splitter.setSizes([1, 1])
  1083. else:
  1084. self.ui.splitter.setSizes([0, 1])
  1085. ####################
  1086. ### Other setups ###
  1087. ####################
  1088. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1089. self.setup_obj_classes()
  1090. self.setup_recent_items()
  1091. self.setup_component_editor()
  1092. #############
  1093. ### Shell ###
  1094. #############
  1095. ###
  1096. # Auto-complete KEYWORDS
  1097. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1098. 'aligndrill', 'clear',
  1099. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1100. 'export_gcode',
  1101. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1102. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1103. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1104. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1105. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1106. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1107. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1108. ]
  1109. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1110. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1111. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1112. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1113. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1114. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1115. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1116. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1117. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1118. ]
  1119. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1120. self.shell = FCShell(self, version=self.version)
  1121. self.shell._edit.set_model_data(self.myKeywords)
  1122. self.shell.setWindowIcon(self.ui.app_icon)
  1123. self.shell.setWindowTitle("FlatCAM Shell")
  1124. self.shell.resize(*self.defaults["global_shell_shape"])
  1125. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1126. self.shell.append_output("(Type help to get started)\n\n")
  1127. self.init_tcl()
  1128. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1129. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1130. self.ui.shell_dock.setWidget(self.shell)
  1131. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1132. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1133. QtWidgets.QDockWidget.DockWidgetFloatable |
  1134. QtWidgets.QDockWidget.DockWidgetClosable)
  1135. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1136. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1137. if self.defaults["global_shell_at_startup"]:
  1138. self.ui.shell_dock.show()
  1139. else:
  1140. self.ui.shell_dock.hide()
  1141. #########################
  1142. ### Tools and Plugins ###
  1143. #########################
  1144. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1145. self.install_tools()
  1146. ### System Font Parsing ###
  1147. # self.f_parse = ParseFont(self)
  1148. # self.parse_system_fonts()
  1149. # test if the program was started with a script as parameter
  1150. if self.cmd_line_shellfile:
  1151. try:
  1152. with open(self.cmd_line_shellfile, "r") as myfile:
  1153. cmd_line_shellfile_text = myfile.read()
  1154. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1155. except Exception as ext:
  1156. print("ERROR: ", ext)
  1157. sys.exit(2)
  1158. ###########################
  1159. #### Check for updates ####
  1160. ###########################
  1161. # Separate thread (Not worker)
  1162. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1163. if (self.beta is False or self.beta is None) and \
  1164. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1165. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1166. self.thr2 = QtCore.QThread()
  1167. self.worker_task.emit({'fcn': self.version_check,
  1168. 'params': []})
  1169. self.thr2.start()
  1170. ####################################
  1171. #### Variables for global usage ####
  1172. ####################################
  1173. # coordinates for relative position display
  1174. self.rel_point1 = (0, 0)
  1175. self.rel_point2 = (0, 0)
  1176. # variable to store coordinates
  1177. self.pos = (0, 0)
  1178. self.pos_jump = (0, 0)
  1179. # variable to store if there was motion before right mouse button click (panning)
  1180. self.panning_action = False
  1181. # variable to store if a command is active (then the var is not None) and which one it is
  1182. self.command_active = None
  1183. # variable to store the status of moving selection action
  1184. # None value means that it's not an selection action
  1185. # True value = a selection from left to right
  1186. # False value = a selection from right to left
  1187. self.selection_type = None
  1188. # List to store the objects that are currently loaded in FlatCAM
  1189. # This list is updated on each object creation or object delete
  1190. self.all_objects_list = []
  1191. # List to store the objects that are selected
  1192. self.sel_objects_list = []
  1193. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1194. self.key_modifiers = None
  1195. # Variable to hold the status of the axis
  1196. self.toggle_axis = True
  1197. # Variable to store the status of the fullscreen event
  1198. self.toggle_fscreen = False
  1199. self.cursor = None
  1200. # Variable to store the GCODE that was edited
  1201. self.gcode_edited = ""
  1202. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1203. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1204. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1205. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1206. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1207. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1208. 'mpf']
  1209. self.svg_list = ['svg']
  1210. self.dxf_list = ['dxf']
  1211. self.prj_list = ['flatprj']
  1212. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1213. # flag for polygons not cleared
  1214. self.poly_not_cleared = False
  1215. ### Save defaults to factory_defaults.FlatConfig file ###
  1216. ### It's done only once after install #############
  1217. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1218. fac_def_from_file = factory_file.read()
  1219. factory_defaults = json.loads(fac_def_from_file)
  1220. # if the file contain an empty dictionary then save the factory defaults into the file
  1221. if not factory_defaults:
  1222. self.save_factory_defaults(silent=False)
  1223. factory_file.close()
  1224. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1225. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1226. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1227. # Post-GUI initialization: Experimental attempt
  1228. # to perform unit tests on the GUI.
  1229. # if post_gui is not None:
  1230. # post_gui(self)
  1231. App.log.debug("END of constructor. Releasing control.")
  1232. # accept a project file as command line parameter
  1233. # the path/file_name must be enclosed in quotes if it contain spaces
  1234. for argument in App.args:
  1235. if '.FlatPrj' in argument:
  1236. try:
  1237. project_name = str(argument)
  1238. if project_name == "":
  1239. self.inform.emit("Open cancelled.")
  1240. else:
  1241. # self.open_project(project_name)
  1242. run_from_arg = True
  1243. self.worker_task.emit({'fcn': self.open_project,
  1244. 'params': [project_name, run_from_arg]})
  1245. except Exception as e:
  1246. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1247. def defaults_read_form(self):
  1248. for option in self.defaults_form_fields:
  1249. try:
  1250. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1251. except:
  1252. pass
  1253. def defaults_write_form(self):
  1254. for option in self.defaults:
  1255. self.defaults_write_form_field(option)
  1256. # try:
  1257. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1258. # except KeyError:
  1259. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1260. # # TODO: Rethink this?
  1261. # pass
  1262. def defaults_write_form_field(self, field):
  1263. try:
  1264. self.defaults_form_fields[field].set_value(self.defaults[field])
  1265. except KeyError:
  1266. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1267. # TODO: Rethink this?
  1268. pass
  1269. def clear_pool(self):
  1270. self.pool.close()
  1271. self.pool = Pool()
  1272. self.pool_recreated.emit(self.pool)
  1273. gc.collect()
  1274. # the order that the tools are installed is important as they can depend on each other install position
  1275. def install_tools(self):
  1276. self.dblsidedtool = DblSidedTool(self)
  1277. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1278. self.measurement_tool = Measurement(self)
  1279. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1280. self.panelize_tool = Panelize(self)
  1281. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1282. self.film_tool = Film(self)
  1283. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1284. self.move_tool = ToolMove(self)
  1285. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1286. before=self.ui.menueditorigin)
  1287. self.cutout_tool = ToolCutOut(self)
  1288. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1289. before=self.measurement_tool.menuAction)
  1290. self.ncclear_tool = NonCopperClear(self)
  1291. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1292. before=self.measurement_tool.menuAction, separator=True)
  1293. self.paint_tool = ToolPaint(self)
  1294. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1295. before=self.measurement_tool.menuAction, separator=True)
  1296. self.calculator_tool = ToolCalculator(self)
  1297. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1298. self.transform_tool = ToolTransform(self)
  1299. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1300. self.properties_tool = Properties(self)
  1301. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1302. self.image_tool = ToolImage(self)
  1303. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1304. separator=True)
  1305. self.log.debug("Tools are installed.")
  1306. def remove_tools(self):
  1307. for act in self.ui.menutool.actions():
  1308. self.ui.menutool.removeAction(act)
  1309. def init_tools(self):
  1310. log.debug("init_tools()")
  1311. # delete the data currently in the Tools Tab and the Tab itself
  1312. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1313. if widget is not None:
  1314. widget.deleteLater()
  1315. self.ui.notebook.removeTab(2)
  1316. # rebuild the Tools Tab
  1317. self.ui.tool_tab = QtWidgets.QWidget()
  1318. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1319. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1320. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1321. self.ui.tool_scroll_area = VerticalScrollArea()
  1322. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1323. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1324. # first remove all of them
  1325. self.remove_tools()
  1326. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1327. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1328. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1329. # third install all of them
  1330. self.install_tools()
  1331. self.log.debug("Tools are initialized.")
  1332. # def parse_system_fonts(self):
  1333. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1334. # 'params': []})
  1335. def object2editor(self):
  1336. """
  1337. Send the current Geometry or Excellon object (if any) into the editor.
  1338. :return: None
  1339. """
  1340. self.report_usage("object2editor()")
  1341. # adjust the visibility of some of the canvas context menu
  1342. self.ui.popmenu_edit.setVisible(False)
  1343. self.ui.popmenu_save.setVisible(True)
  1344. edited_object = self.collection.get_active()
  1345. if isinstance(edited_object, FlatCAMGeometry):
  1346. # for now, if the Geometry is MultiGeo do not allow the editing
  1347. if edited_object.multigeo is True:
  1348. self.inform.emit("[WARNING_NOTCL]Editing a MultiGeo Geometry is not possible for the moment.")
  1349. return
  1350. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1351. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1352. self.geo_editor.edit_fcgeometry(edited_object)
  1353. # set call source to the Editor we go into
  1354. self.call_source = 'geo_editor'
  1355. elif isinstance(edited_object, FlatCAMExcellon):
  1356. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1357. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1358. self.exc_editor.edit_fcexcellon(edited_object)
  1359. # set call source to the Editor we go into
  1360. self.call_source = 'exc_editor'
  1361. else:
  1362. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit.")
  1363. return
  1364. # make sure that we can't select another object while in Editor Mode:
  1365. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1366. # delete any selection shape that might be active as they are not relevant in Editor
  1367. self.delete_selection_shape()
  1368. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1369. self.ui.plot_tab_area.protectTab(0)
  1370. self.inform.emit("[WARNING_NOTCL]Editor is activated ...")
  1371. def editor2object(self):
  1372. """
  1373. Transfers the Geometry or Excellon from the editor to the current object.
  1374. :return: None
  1375. """
  1376. self.report_usage("editor2object()")
  1377. # adjust the visibility of some of the canvas context menu
  1378. self.ui.popmenu_edit.setVisible(True)
  1379. self.ui.popmenu_save.setVisible(False)
  1380. edited_obj = self.collection.get_active()
  1381. obj_type = ""
  1382. if isinstance(edited_obj, FlatCAMGeometry):
  1383. obj_type = "Geometry"
  1384. self.geo_editor.update_fcgeometry(edited_obj)
  1385. self.geo_editor.update_options(edited_obj)
  1386. self.geo_editor.deactivate()
  1387. # update the geo object options so it is including the bounding box values
  1388. try:
  1389. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1390. edited_obj.options['xmin'] = xmin
  1391. edited_obj.options['ymin'] = ymin
  1392. edited_obj.options['xmax'] = xmax
  1393. edited_obj.options['ymax'] = ymax
  1394. except AttributeError:
  1395. self.inform.emit("[WARNING] Object empty after edit.")
  1396. elif isinstance(edited_obj, FlatCAMExcellon):
  1397. obj_type = "Excellon"
  1398. self.exc_editor.update_fcexcellon(edited_obj)
  1399. self.exc_editor.update_options(edited_obj)
  1400. self.exc_editor.deactivate()
  1401. else:
  1402. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to update.")
  1403. return
  1404. # restore the call_source to app
  1405. self.call_source = 'app'
  1406. edited_obj.plot()
  1407. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1408. self.ui.plot_tab_area.protectTab(0)
  1409. self.inform.emit("[selected] %s is updated, returning to App..." % obj_type)
  1410. # reset the Object UI to original settings
  1411. # edited_obj.set_ui(edited_obj.ui_type())
  1412. # edited_obj.build_ui()
  1413. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1414. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1415. def get_last_folder(self):
  1416. return self.defaults["global_last_folder"]
  1417. def get_last_save_folder(self):
  1418. loc = self.defaults["global_last_save_folder"]
  1419. if loc is None:
  1420. loc = self.defaults["global_last_folder"]
  1421. if loc is None:
  1422. loc = os.path.dirname(__file__)
  1423. return loc
  1424. def report_usage(self, resource):
  1425. """
  1426. Increments usage counter for the given resource
  1427. in self.defaults['global_stats'].
  1428. :param resource: Name of the resource.
  1429. :return: None
  1430. """
  1431. if resource in self.defaults['global_stats']:
  1432. self.defaults['global_stats'][resource] += 1
  1433. else:
  1434. self.defaults['global_stats'][resource] = 1
  1435. def init_tcl(self):
  1436. if hasattr(self,'tcl'):
  1437. # self.tcl = None
  1438. # TODO we need to clean non default variables and procedures here
  1439. # new object cannot be used here as it will not remember values created for next passes,
  1440. # because tcl was execudted in old instance of TCL
  1441. pass
  1442. else:
  1443. self.tcl = tk.Tcl()
  1444. self.setup_shell()
  1445. self.log.debug("TCL Shell has been initialized.")
  1446. # TODO: This shouldn't be here.
  1447. class TclErrorException(Exception):
  1448. """
  1449. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1450. """
  1451. pass
  1452. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1453. """
  1454. Shows a message on the FlatCAM Shell
  1455. :param msg: Message to display.
  1456. :param show: Opens the shell.
  1457. :param error: Shows the message as an error.
  1458. :return: None
  1459. """
  1460. if show:
  1461. self.ui.shell_dock.show()
  1462. try:
  1463. if error:
  1464. self.shell.append_error(msg + "\n")
  1465. elif warning:
  1466. self.shell.append_warning(msg + "\n")
  1467. elif success:
  1468. self.shell.append_success(msg + "\n")
  1469. elif selected:
  1470. self.shell.append_selected(msg + "\n")
  1471. else:
  1472. self.shell.append_output(msg + "\n")
  1473. except AttributeError:
  1474. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1475. def raise_tcl_unknown_error(self, unknownException):
  1476. """
  1477. Raise exception if is different type than TclErrorException
  1478. this is here mainly to show unknown errors inside TCL shell console.
  1479. :param unknownException:
  1480. :return:
  1481. """
  1482. if not isinstance(unknownException, self.TclErrorException):
  1483. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1484. else:
  1485. raise unknownException
  1486. def display_tcl_error(self, error, error_info=None):
  1487. """
  1488. escape bracket [ with \ otherwise there is error
  1489. "ERROR: missing close-bracket" instead of real error
  1490. :param error: it may be text or exception
  1491. :return: None
  1492. """
  1493. if isinstance(error, Exception):
  1494. exc_type, exc_value, exc_traceback = error_info
  1495. if not isinstance(error, self.TclErrorException):
  1496. show_trace = 1
  1497. else:
  1498. show_trace = int(self.defaults['global_verbose_error_level'])
  1499. if show_trace > 0:
  1500. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1501. trc_formated = []
  1502. for a in reversed(trc):
  1503. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1504. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1505. exc_type,
  1506. "\n".join(trc_formated))
  1507. else:
  1508. text = "%s" % error
  1509. else:
  1510. text = error
  1511. text = text.replace('[', '\\[').replace('"', '\\"')
  1512. self.tcl.eval('return -code error "%s"' % text)
  1513. def raise_tcl_error(self, text):
  1514. """
  1515. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1516. :param text: text of error
  1517. :return: raise exception
  1518. """
  1519. self.display_tcl_error(text)
  1520. raise self.TclErrorException(text)
  1521. def exec_command(self, text):
  1522. """
  1523. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1524. Also handles execution in separated threads
  1525. :param text:
  1526. :return: output if there was any
  1527. """
  1528. self.report_usage('exec_command')
  1529. result = self.exec_command_test(text, False)
  1530. #MS: added this method call so the geometry is updated once the TCL
  1531. #command is executed
  1532. self.plot_all()
  1533. return result
  1534. def exec_command_test(self, text, reraise=True):
  1535. """
  1536. Same as exec_command(...) with additional control over exceptions.
  1537. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1538. :param text: Input command
  1539. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1540. :return: Output from the command
  1541. """
  1542. text = str(text)
  1543. try:
  1544. self.shell.open_proccessing() # Disables input box.
  1545. result = self.tcl.eval(str(text))
  1546. if result != 'None':
  1547. self.shell.append_output(result + '\n')
  1548. except tk.TclError as e:
  1549. # This will display more precise answer if something in TCL shell fails
  1550. result = self.tcl.eval("set errorInfo")
  1551. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1552. self.shell.append_error('ERROR: ' + result + '\n')
  1553. # Show error in console and just return or in test raise exception
  1554. if reraise:
  1555. raise e
  1556. finally:
  1557. self.shell.close_proccessing()
  1558. pass
  1559. return result
  1560. # """
  1561. # Code below is unsused. Saved for later.
  1562. # """
  1563. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1564. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1565. # self.log.debug(parts)
  1566. # try:
  1567. # if parts[0] not in commands:
  1568. # self.shell.append_error("Unknown command\n")
  1569. # return
  1570. #
  1571. # #import inspect
  1572. # #inspect.getargspec(someMethod)
  1573. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1574. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1575. # self.shell.append_error(
  1576. # "Command %s takes %d arguments. %d given.\n" %
  1577. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1578. # )
  1579. # return
  1580. #
  1581. # cmdfcn = commands[parts[0]]["fcn"]
  1582. # cmdconv = commands[parts[0]]["converters"]
  1583. # if len(parts) - 1 > 0:
  1584. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1585. # else:
  1586. # retval = cmdfcn()
  1587. # retfcn = commands[parts[0]]["retfcn"]
  1588. # if retval and retfcn(retval):
  1589. # self.shell.append_output(retfcn(retval) + "\n")
  1590. #
  1591. # except Exception as e:
  1592. # #self.shell.append_error(''.join(traceback.format_exc()))
  1593. # #self.shell.append_error("?\n")
  1594. # self.shell.append_error(str(e) + "\n")
  1595. def info(self, msg):
  1596. """
  1597. Informs the user. Normally on the status bar, optionally
  1598. also on the shell.
  1599. :param msg: Text to write.
  1600. :return: None
  1601. """
  1602. # Type of message in brackets at the begining of the message.
  1603. match = re.search("\[([^\]]+)\](.*)", msg)
  1604. if match:
  1605. level = match.group(1)
  1606. msg_ = match.group(2)
  1607. self.ui.fcinfo.set_status(str(msg_), level=level)
  1608. if level.lower() == "error":
  1609. self.shell_message(msg, error=True, show=True)
  1610. elif level.lower() == "warning":
  1611. self.shell_message(msg, warning=True, show=True)
  1612. elif level.lower() == "error_notcl":
  1613. self.shell_message(msg, error=True, show=False)
  1614. elif level.lower() == "warning_notcl":
  1615. self.shell_message(msg, warning=True, show=False)
  1616. elif level.lower() == "success":
  1617. self.shell_message(msg, success=True, show=False)
  1618. elif level.lower() == "selected":
  1619. self.shell_message(msg, selected=True, show=False)
  1620. else:
  1621. self.shell_message(msg, show=False)
  1622. else:
  1623. self.ui.fcinfo.set_status(str(msg), level="info")
  1624. # make sure that if the message is to clear the infobar with a space
  1625. # is not printed over and over on the shell
  1626. if msg != '':
  1627. self.shell_message(msg)
  1628. def restore_toolbar_view(self):
  1629. tb = self.defaults["global_toolbar_view"]
  1630. if tb & 1:
  1631. self.ui.toolbarfile.setVisible(True)
  1632. else:
  1633. self.ui.toolbarfile.setVisible(False)
  1634. if tb & 2:
  1635. self.ui.toolbargeo.setVisible(True)
  1636. else:
  1637. self.ui.toolbargeo.setVisible(False)
  1638. if tb & 4:
  1639. self.ui.toolbarview.setVisible(True)
  1640. else:
  1641. self.ui.toolbarview.setVisible(False)
  1642. if tb & 8:
  1643. self.ui.toolbartools.setVisible(True)
  1644. else:
  1645. self.ui.toolbartools.setVisible(False)
  1646. if tb & 16:
  1647. self.ui.exc_edit_toolbar.setVisible(True)
  1648. else:
  1649. self.ui.exc_edit_toolbar.setVisible(False)
  1650. if tb & 32:
  1651. self.ui.geo_edit_toolbar.setVisible(True)
  1652. else:
  1653. self.ui.geo_edit_toolbar.setVisible(False)
  1654. if tb & 64:
  1655. self.ui.snap_toolbar.setVisible(True)
  1656. else:
  1657. self.ui.snap_toolbar.setVisible(False)
  1658. def load_defaults(self, filename):
  1659. """
  1660. Loads the aplication's default settings from current_defaults.FlatConfig into
  1661. ``self.defaults``.
  1662. :return: None
  1663. """
  1664. try:
  1665. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1666. options = f.read()
  1667. f.close()
  1668. except IOError:
  1669. self.log.error("Could not load defaults file.")
  1670. self.inform.emit("[ERROR] Could not load defaults file.")
  1671. # in case the defaults file can't be loaded, show all toolbars
  1672. self.defaults["global_toolbar_view"] = 127
  1673. return
  1674. try:
  1675. defaults = json.loads(options)
  1676. except:
  1677. # in case the defaults file can't be loaded, show all toolbars
  1678. self.defaults["global_toolbar_view"] = 127
  1679. e = sys.exc_info()[0]
  1680. App.log.error(str(e))
  1681. self.inform.emit("[ERROR] Failed to parse defaults file.")
  1682. return
  1683. self.defaults.update(defaults)
  1684. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1685. # restore the toolbar view
  1686. self.restore_toolbar_view()
  1687. def on_import_preferences(self):
  1688. """
  1689. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1690. ``self.defaults``.
  1691. :return: None
  1692. """
  1693. self.report_usage("on_import_preferences")
  1694. App.log.debug("on_import_preferences()")
  1695. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1696. try:
  1697. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1698. directory=self.data_path, filter=filter)
  1699. except TypeError:
  1700. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1701. filename = str(filename)
  1702. if filename == "":
  1703. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences import cancelled.")
  1704. else:
  1705. try:
  1706. f = open(filename)
  1707. options = f.read()
  1708. f.close()
  1709. except IOError:
  1710. self.log.error("Could not load defaults file.")
  1711. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  1712. return
  1713. try:
  1714. defaults_from_file = json.loads(options)
  1715. except:
  1716. e = sys.exc_info()[0]
  1717. App.log.error(str(e))
  1718. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  1719. return
  1720. self.defaults.update(defaults_from_file)
  1721. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1722. def on_export_preferences(self):
  1723. self.report_usage("on_export_preferences")
  1724. App.log.debug("on_export_preferences()")
  1725. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1726. try:
  1727. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  1728. caption="Export FlatCAM Preferences",
  1729. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1730. )
  1731. except TypeError:
  1732. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1733. filename = str(filename)
  1734. defaults_from_file = {}
  1735. if filename == "":
  1736. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences export cancelled.")
  1737. return
  1738. else:
  1739. try:
  1740. f = open(filename, 'w')
  1741. defaults_file_content = f.read()
  1742. f.close()
  1743. except IOError:
  1744. App.log.debug('Creating a new preferences file ...')
  1745. f = open(filename, 'w')
  1746. json.dump({}, f)
  1747. f.close()
  1748. except:
  1749. e = sys.exc_info()[0]
  1750. App.log.error("Could not load defaults file.")
  1751. App.log.error(str(e))
  1752. self.inform.emit("[ERROR_NOTCL]Could not load defaults file.")
  1753. return
  1754. try:
  1755. defaults_from_file = json.loads(defaults_file_content)
  1756. except:
  1757. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1758. # Update options
  1759. self.defaults_read_form()
  1760. defaults_from_file.update(self.defaults)
  1761. self.propagate_defaults(silent=True)
  1762. # Save update options
  1763. try:
  1764. f = open(filename, "w")
  1765. json.dump(defaults_from_file, f)
  1766. f.close()
  1767. except:
  1768. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  1769. return
  1770. self.file_saved.emit("preferences", filename)
  1771. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1772. def on_preferences_open_folder(self):
  1773. self.report_usage("on_preferences_open_folder()")
  1774. if sys.platform == 'win32':
  1775. subprocess.Popen('explorer %s' % self.data_path)
  1776. elif sys.platform == 'darwin':
  1777. os.system('open "%s"' % self.data_path)
  1778. else:
  1779. subprocess.Popen(['xdg-open', self.data_path])
  1780. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1781. def save_geometry(self, x, y, width, height, notebook_width):
  1782. self.defaults["global_def_win_x"] = x
  1783. self.defaults["global_def_win_y"] = y
  1784. self.defaults["global_def_win_w"] = width
  1785. self.defaults["global_def_win_h"] = height
  1786. self.defaults["def_notebook_width"] = notebook_width
  1787. self.save_defaults()
  1788. def message_dialog(self, title, message, kind="info"):
  1789. icon = {"info": QtWidgets.QMessageBox.Information,
  1790. "warning": QtWidgets.QMessageBox.Warning,
  1791. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1792. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1793. dlg.setText(message)
  1794. dlg.exec_()
  1795. def register_recent(self, kind, filename):
  1796. self.log.debug("register_recent()")
  1797. self.log.debug(" %s" % kind)
  1798. self.log.debug(" %s" % filename)
  1799. record = {'kind': str(kind), 'filename': str(filename)}
  1800. if record in self.recent:
  1801. return
  1802. self.recent.insert(0, record)
  1803. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1804. self.recent.pop()
  1805. try:
  1806. f = open(self.data_path + '/recent.json', 'w')
  1807. except IOError:
  1808. App.log.error("Failed to open recent items file for writing.")
  1809. self.inform.emit('[ERROR_NOTCL]Failed to open recent files file for writing.')
  1810. return
  1811. #try:
  1812. json.dump(self.recent, f)
  1813. # except:
  1814. # App.log.error("Failed to write to recent items file.")
  1815. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1816. # f.close()
  1817. f.close()
  1818. # Re-buid the recent items menu
  1819. self.setup_recent_items()
  1820. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1821. """
  1822. Creates a new specalized FlatCAMObj and attaches it to the application,
  1823. this is, updates the GUI accordingly, any other records and plots it.
  1824. This method is thread-safe.
  1825. Notes:
  1826. * If the name is in use, the self.collection will modify it
  1827. when appending it to the collection. There is no need to handle
  1828. name conflicts here.
  1829. :param kind: The kind of object to create. One of 'gerber',
  1830. 'excellon', 'cncjob' and 'geometry'.
  1831. :type kind: str
  1832. :param name: Name for the object.
  1833. :type name: str
  1834. :param initialize: Function to run after creation of the object
  1835. but before it is attached to the application. The function is
  1836. called with 2 parameters: the new object and the App instance.
  1837. :type initialize: function
  1838. :return: None
  1839. :rtype: None
  1840. """
  1841. App.log.debug("new_object()")
  1842. self.plot = plot
  1843. self.autoselected = autoselected
  1844. t0 = time.time() # Debug
  1845. ## Create object
  1846. classdict = {
  1847. "gerber": FlatCAMGerber,
  1848. "excellon": FlatCAMExcellon,
  1849. "cncjob": FlatCAMCNCjob,
  1850. "geometry": FlatCAMGeometry
  1851. }
  1852. App.log.debug("Calling object constructor...")
  1853. obj = classdict[kind](name)
  1854. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1855. # Set options from "Project options" form
  1856. self.options_read_form()
  1857. # IMPORTANT
  1858. # The key names in defaults and options dictionary's are not random:
  1859. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1860. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1861. # the options from project options form into the self.options. After that, below, depending on the type of
  1862. # object that is created, it will strip the name of the object and the underline (if the original key was
  1863. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1864. # "toolchange"
  1865. for option in self.options:
  1866. if option.find(kind + "_") == 0:
  1867. oname = option[len(kind) + 1:]
  1868. obj.options[oname] = self.options[option]
  1869. # if kind == 'geometry':
  1870. # obj.tools = {}
  1871. # elif kind == 'cncjob':
  1872. # obj.cnc_tools = {}
  1873. # Initialize as per user request
  1874. # User must take care to implement initialize
  1875. # in a thread-safe way as is is likely that we
  1876. # have been invoked in a separate thread.
  1877. t1 = time.time()
  1878. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1879. try:
  1880. return_value = initialize(obj, self)
  1881. except Exception as e:
  1882. msg = "[ERROR_NOTCL] An internal error has ocurred. See shell.\n"
  1883. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1884. msg += traceback.format_exc()
  1885. self.inform.emit(msg)
  1886. # if str(e) == "Empty Geometry":
  1887. # self.inform.emit("[ERROR_NOTCL] )
  1888. # else:
  1889. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  1890. return "fail"
  1891. t2 = time.time()
  1892. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1893. if return_value == 'fail':
  1894. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1895. return "fail"
  1896. # Check units and convert if necessary
  1897. # This condition CAN be true because initialize() can change obj.units
  1898. if self.options["units"].upper() != obj.units.upper():
  1899. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1900. obj.convert_units(self.options["units"])
  1901. t3 = time.time()
  1902. self.log.debug("%f seconds converting units." % (t3 - t2))
  1903. # Create the bounding box for the object and then add the results to the obj.options
  1904. try:
  1905. xmin, ymin, xmax, ymax = obj.bounds()
  1906. obj.options['xmin'] = xmin
  1907. obj.options['ymin'] = ymin
  1908. obj.options['xmax'] = xmax
  1909. obj.options['ymax'] = ymax
  1910. except:
  1911. log.warning("The object has no bounds properties.")
  1912. # don't plot objects with no bounds, there is nothing to plot
  1913. self.plot = False
  1914. pass
  1915. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1916. # Move the object to the main thread and let the app know that it is available.
  1917. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1918. self.object_created.emit(obj, self.plot, self.autoselected)
  1919. return obj
  1920. def new_excellon_object(self):
  1921. self.report_usage("new_excellon_object()")
  1922. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  1923. def new_geometry_object(self):
  1924. self.report_usage("new_geometry_object()")
  1925. def initialize(obj, self):
  1926. obj.multitool = False
  1927. self.new_object('geometry', 'new_g', initialize, plot=False)
  1928. def on_object_created(self, obj, plot, autoselect):
  1929. """
  1930. Event callback for object creation.
  1931. :param obj: The newly created FlatCAM object.
  1932. :return: None
  1933. """
  1934. t0 = time.time() # DEBUG
  1935. self.log.debug("on_object_created()")
  1936. # The Collection might change the name if there is a collision
  1937. self.collection.append(obj)
  1938. # after adding the object to the collection always update the list of objects that are in the collection
  1939. self.all_objects_list = self.collection.get_list()
  1940. # self.inform.emit('[selected] %s created & selected: %s' %
  1941. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  1942. if obj.kind == 'gerber':
  1943. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1944. (obj.kind.capitalize(), 'green', str(obj.options['name'])))
  1945. elif obj.kind == 'excellon':
  1946. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1947. (obj.kind.capitalize(), 'brown', str(obj.options['name'])))
  1948. elif obj.kind == 'cncjob':
  1949. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1950. (obj.kind.capitalize(), 'blue', str(obj.options['name'])))
  1951. elif obj.kind == 'geometry':
  1952. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1953. (obj.kind.capitalize(), 'red', str(obj.options['name'])))
  1954. # self.new_object_available.emit(obj)
  1955. # update the SHELL auto-completer model with the name of the new object
  1956. self.myKeywords.append(obj.options['name'])
  1957. self.shell._edit.set_model_data(self.myKeywords)
  1958. if autoselect:
  1959. # select the just opened object but deselect the previous ones
  1960. self.collection.set_all_inactive()
  1961. self.collection.set_active(obj.options["name"])
  1962. # here it is done the object plotting
  1963. def worker_task(obj):
  1964. with self.proc_container.new("Plotting"):
  1965. if isinstance(obj, FlatCAMCNCjob):
  1966. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  1967. else:
  1968. obj.plot()
  1969. t1 = time.time() # DEBUG
  1970. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1971. self.object_plotted.emit(obj)
  1972. # Send to worker
  1973. # self.worker.add_task(worker_task, [self])
  1974. if plot is True:
  1975. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1976. def on_object_changed(self, obj):
  1977. # update the bounding box data from obj.options
  1978. xmin, ymin, xmax, ymax = obj.bounds()
  1979. obj.options['xmin'] = xmin
  1980. obj.options['ymin'] = ymin
  1981. obj.options['xmax'] = xmax
  1982. obj.options['ymax'] = ymax
  1983. log.debug("Object changed, updating the bounding box data on self.options")
  1984. # delete the old selection shape
  1985. self.delete_selection_shape()
  1986. def on_object_plotted(self, obj):
  1987. self.on_zoom_fit(None)
  1988. def options_read_form(self):
  1989. for option in self.options_form_fields:
  1990. self.options[option] = self.options_form_fields[option].get_value()
  1991. def options_write_form(self):
  1992. for option in self.options:
  1993. self.options_write_form_field(option)
  1994. def options_write_form_field(self, field):
  1995. try:
  1996. self.options_form_fields[field].set_value(self.options[field])
  1997. except KeyError:
  1998. # Changed from error to debug. This allows to have data stored
  1999. # which is not user-editable.
  2000. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2001. pass
  2002. def on_about(self):
  2003. """
  2004. Displays the "about" dialog.
  2005. :return: None
  2006. """
  2007. self.report_usage("on_about")
  2008. version = self.version
  2009. version_date = self.version_date
  2010. beta = self.beta
  2011. class AboutDialog(QtWidgets.QDialog):
  2012. def __init__(self, parent=None):
  2013. QtWidgets.QDialog.__init__(self, parent)
  2014. # Icon and title
  2015. self.setWindowIcon(parent.app_icon)
  2016. self.setWindowTitle("FlatCAM")
  2017. layout1 = QtWidgets.QVBoxLayout()
  2018. self.setLayout(layout1)
  2019. layout2 = QtWidgets.QHBoxLayout()
  2020. layout1.addLayout(layout2)
  2021. logo = QtWidgets.QLabel()
  2022. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2023. layout2.addWidget(logo, stretch=0)
  2024. title = QtWidgets.QLabel(
  2025. "<font size=8><B>FlatCAM</B></font><BR>"
  2026. "Version %s %s (%s) - %s <BR>"
  2027. "<BR>"
  2028. "2D Computer-Aided Printed Circuit Board<BR>"
  2029. "Manufacturing.<BR>"
  2030. "<BR>"
  2031. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2032. "<BR>"
  2033. "<B> Main Contributors:</B><BR>"
  2034. "Denis Hayrullin<BR>"
  2035. "Kamil Sopko<BR>"
  2036. "Marius Stanciu<BR>"
  2037. "Matthieu Berthomé<BR>"
  2038. "and many others found "
  2039. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2040. "<BR>"
  2041. "Development is done "
  2042. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2043. "DOWNLOAD area "
  2044. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2045. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  2046. )
  2047. title.setOpenExternalLinks(True)
  2048. layout2.addWidget(title, stretch=1)
  2049. layout3 = QtWidgets.QHBoxLayout()
  2050. layout1.addLayout(layout3)
  2051. layout3.addStretch()
  2052. okbtn = QtWidgets.QPushButton("Close")
  2053. layout3.addWidget(okbtn)
  2054. okbtn.clicked.connect(self.accept)
  2055. AboutDialog(self.ui).exec_()
  2056. def on_file_savedefaults(self):
  2057. """
  2058. Callback for menu item File->Save Defaults. Saves application default options
  2059. ``self.defaults`` to current_defaults.FlatConfig.
  2060. :return: None
  2061. """
  2062. self.save_defaults()
  2063. def on_app_exit(self):
  2064. self.report_usage("on_app_exit()")
  2065. if self.collection.get_list():
  2066. msgbox = QtWidgets.QMessageBox()
  2067. # msgbox.setText("<B>Save changes ...</B>")
  2068. msgbox.setText("There are files/objects opened in FlatCAM. "
  2069. "\n"
  2070. "Do you want to Save the project?")
  2071. msgbox.setWindowTitle("Save changes")
  2072. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2073. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2074. QtWidgets.QMessageBox.Cancel)
  2075. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2076. response = msgbox.exec_()
  2077. if response == QtWidgets.QMessageBox.Yes:
  2078. self.on_file_saveprojectas(thread=False)
  2079. elif response == QtWidgets.QMessageBox.Cancel:
  2080. return
  2081. self.save_defaults()
  2082. else:
  2083. self.save_defaults()
  2084. log.debug("Application defaults saved ... Exit event.")
  2085. QtWidgets.qApp.quit()
  2086. def save_defaults(self, silent=False):
  2087. """
  2088. Saves application default options
  2089. ``self.defaults`` to current_defaults.FlatConfig.
  2090. :return: None
  2091. """
  2092. self.report_usage("save_defaults")
  2093. # Read options from file
  2094. try:
  2095. f = open(self.data_path + "/current_defaults.FlatConfig")
  2096. defaults_file_content = f.read()
  2097. f.close()
  2098. except:
  2099. e = sys.exc_info()[0]
  2100. App.log.error("Could not load defaults file.")
  2101. App.log.error(str(e))
  2102. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  2103. return
  2104. try:
  2105. defaults = json.loads(defaults_file_content)
  2106. except:
  2107. e = sys.exc_info()[0]
  2108. App.log.error("Failed to parse defaults file.")
  2109. App.log.error(str(e))
  2110. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  2111. return
  2112. # Update options
  2113. self.defaults_read_form()
  2114. defaults.update(self.defaults)
  2115. self.propagate_defaults(silent=True)
  2116. # Save update options
  2117. try:
  2118. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2119. json.dump(defaults, f)
  2120. f.close()
  2121. except:
  2122. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  2123. return
  2124. # Save the toolbar view
  2125. tb_status = 0
  2126. if self.ui.toolbarfile.isVisible():
  2127. tb_status += 1
  2128. if self.ui.toolbargeo.isVisible():
  2129. tb_status += 2
  2130. if self.ui.toolbarview.isVisible():
  2131. tb_status += 4
  2132. if self.ui.toolbartools.isVisible():
  2133. tb_status += 8
  2134. if self.ui.exc_edit_toolbar.isVisible():
  2135. tb_status += 16
  2136. if self.ui.geo_edit_toolbar.isVisible():
  2137. tb_status += 32
  2138. if self.ui.snap_toolbar.isVisible():
  2139. tb_status += 64
  2140. self.defaults["global_toolbar_view"] = tb_status
  2141. if not silent:
  2142. self.inform.emit("[success]Defaults saved.")
  2143. def save_factory_defaults(self, silent=False):
  2144. """
  2145. Saves application factory default options
  2146. ``self.defaults`` to factory_defaults.FlatConfig.
  2147. It's a one time job done just after the first install.
  2148. :return: None
  2149. """
  2150. self.report_usage("save_factory_defaults")
  2151. # Read options from file
  2152. try:
  2153. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2154. factory_defaults_file_content = f_f_def.read()
  2155. f_f_def.close()
  2156. except:
  2157. e = sys.exc_info()[0]
  2158. App.log.error("Could not load factory defaults file.")
  2159. App.log.error(str(e))
  2160. self.inform.emit("[ERROR_NOTCL] Could not load factory defaults file.")
  2161. return
  2162. try:
  2163. factory_defaults = json.loads(factory_defaults_file_content)
  2164. except:
  2165. e = sys.exc_info()[0]
  2166. App.log.error("Failed to parse factory defaults file.")
  2167. App.log.error(str(e))
  2168. self.inform.emit("[ERROR_NOTCL] Failed to parse factory defaults file.")
  2169. return
  2170. # Update options
  2171. self.defaults_read_form()
  2172. factory_defaults.update(self.defaults)
  2173. self.propagate_defaults(silent=True)
  2174. # Save update options
  2175. try:
  2176. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2177. json.dump(factory_defaults, f_f_def_s)
  2178. f_f_def_s.close()
  2179. except:
  2180. self.inform.emit("[ERROR_NOTCL] Failed to write factory defaults to file.")
  2181. return
  2182. if silent is False:
  2183. self.inform.emit("Factory defaults saved.")
  2184. def final_save(self):
  2185. if self.collection.get_list():
  2186. msgbox = QtWidgets.QMessageBox()
  2187. # msgbox.setText("<B>Save changes ...</B>")
  2188. msgbox.setText("There are files/objects opened in FlatCAM. "
  2189. "\n"
  2190. "Do you want to Save the project?")
  2191. msgbox.setWindowTitle("Save changes")
  2192. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2193. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2194. QtWidgets.QMessageBox.Cancel)
  2195. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2196. response = msgbox.exec_()
  2197. if response == QtWidgets.QMessageBox.Yes:
  2198. self.on_file_saveprojectas(thread=False)
  2199. elif response == QtWidgets.QMessageBox.Cancel:
  2200. self.should_we_quit = False
  2201. return
  2202. self.save_defaults()
  2203. log.debug("Application defaults saved ... Exit event.")
  2204. def on_toggle_shell(self):
  2205. """
  2206. toggle shell if is visible close it if closed open it
  2207. :return:
  2208. """
  2209. self.report_usage("on_toggle_shell()")
  2210. if self.ui.shell_dock.isVisible():
  2211. self.ui.shell_dock.hide()
  2212. else:
  2213. self.ui.shell_dock.show()
  2214. def on_edit_join(self, name=None):
  2215. """
  2216. Callback for Edit->Join. Joins the selected geometry objects into
  2217. a new one.
  2218. :return: None
  2219. """
  2220. self.report_usage("on_edit_join()")
  2221. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2222. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2223. tooldias = []
  2224. geo_type_list = []
  2225. objs = self.collection.get_selected()
  2226. for obj in objs:
  2227. geo_type_list.append(obj.multigeo)
  2228. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2229. if len(set(geo_type_list)) != 1:
  2230. self.inform.emit("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2231. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2232. "convert from one to another and retry joining \n"
  2233. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2234. "the result may not be what was expected. \n"
  2235. "Check the generated GCODE.")
  2236. return
  2237. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2238. if True in geo_type_list:
  2239. def initialize(obj, app):
  2240. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2241. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2242. for v in obj.tools.values():
  2243. v['data']['name'] = obj_name_multi
  2244. self.new_object("geometry", obj_name_multi, initialize)
  2245. else:
  2246. def initialize(obj, app):
  2247. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2248. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2249. for v in obj.tools.values():
  2250. v['data']['name'] = obj_name_single
  2251. self.new_object("geometry", obj_name_single, initialize)
  2252. def on_edit_join_exc(self):
  2253. """
  2254. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2255. a new one.
  2256. :return: None
  2257. """
  2258. self.report_usage("on_edit_join_exc()")
  2259. objs = self.collection.get_selected()
  2260. for obj in objs:
  2261. if not isinstance(obj, FlatCAMExcellon):
  2262. self.inform.emit("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects.")
  2263. return
  2264. def initialize(obj, app):
  2265. FlatCAMExcellon.merge(objs, obj)
  2266. self.new_object("excellon", 'Combo_Excellon', initialize)
  2267. def on_edit_join_grb(self):
  2268. """
  2269. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2270. a new one.
  2271. :return: None
  2272. """
  2273. self.report_usage("on_edit_join_grb()")
  2274. objs = self.collection.get_selected()
  2275. for obj in objs:
  2276. if not isinstance(obj, FlatCAMGerber):
  2277. self.inform.emit("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects.")
  2278. return
  2279. def initialize(obj, app):
  2280. FlatCAMGerber.merge(objs, obj)
  2281. self.new_object("gerber", 'Combo_Gerber', initialize)
  2282. def on_convert_singlegeo_to_multigeo(self):
  2283. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2284. obj = self.collection.get_active()
  2285. if obj is None:
  2286. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2287. return
  2288. if not isinstance(obj, FlatCAMGeometry):
  2289. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2290. return
  2291. obj.multigeo = True
  2292. for tooluid, dict_value in obj.tools.items():
  2293. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2294. if not isinstance(obj.solid_geometry, list):
  2295. obj.solid_geometry = [obj.solid_geometry]
  2296. obj.solid_geometry[:] = []
  2297. obj.plot()
  2298. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2299. def on_convert_multigeo_to_singlegeo(self):
  2300. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2301. obj = self.collection.get_active()
  2302. if obj is None:
  2303. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2304. return
  2305. if not isinstance(obj, FlatCAMGeometry):
  2306. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2307. return
  2308. obj.multigeo = False
  2309. total_solid_geometry = []
  2310. for tooluid, dict_value in obj.tools.items():
  2311. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2312. # clear the original geometry
  2313. dict_value['solid_geometry'][:] = []
  2314. obj.solid_geometry = deepcopy(total_solid_geometry)
  2315. obj.plot()
  2316. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2317. def on_options_dict_change(self, field):
  2318. self.options_write_form_field(field)
  2319. if field == "units":
  2320. self.set_screen_units(self.options['units'])
  2321. def on_defaults_dict_change(self, field):
  2322. self.defaults_write_form_field(field)
  2323. def set_screen_units(self, units):
  2324. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2325. def on_toggle_units(self):
  2326. """
  2327. Callback for the Units radio-button change in the Options tab.
  2328. Changes the application's default units or the current project's units.
  2329. If changing the project's units, the change propagates to all of
  2330. the objects in the project.
  2331. :return: None
  2332. """
  2333. self.report_usage("on_toggle_units")
  2334. if self.toggle_units_ignore:
  2335. return
  2336. # If option is the same, then ignore
  2337. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2338. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2339. return
  2340. # Options to scale
  2341. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2342. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2343. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2344. 'gerber_noncoppermargin','gerber_bboxmargin',
  2345. 'excellon_drillz', "excellon_toolchangexy",
  2346. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2347. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2348. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2349. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2350. 'geometry_toolchangez',
  2351. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2352. def scale_options(sfactor):
  2353. for dim in dimensions:
  2354. if dim == 'excellon_toolchangexy':
  2355. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2356. coords_xy[0] *= sfactor
  2357. coords_xy[1] *= sfactor
  2358. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2359. elif dim == 'geometry_toolchangexy':
  2360. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2361. coords_xy[0] *= sfactor
  2362. coords_xy[1] *= sfactor
  2363. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2364. else:
  2365. self.options[dim] *= sfactor
  2366. # The scaling factor depending on choice of units.
  2367. factor = 1/25.4
  2368. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2369. factor = 25.4
  2370. # Changing project units. Warn user.
  2371. msgbox = QtWidgets.QMessageBox()
  2372. msgbox.setText("<B>Change project units ...</B>")
  2373. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2374. "properties of all objects to be scaled accordingly. Continue?")
  2375. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2376. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2377. response = msgbox.exec_()
  2378. if response == QtWidgets.QMessageBox.Ok:
  2379. self.options_read_form()
  2380. scale_options(factor)
  2381. self.options_write_form()
  2382. # change this only if the workspace is active
  2383. if self.defaults['global_workspace'] is True:
  2384. self.plotcanvas.draw_workspace()
  2385. # adjust the grid values on the main toolbar
  2386. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2387. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2388. for obj in self.collection.get_list():
  2389. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2390. obj.convert_units(units)
  2391. # make that the properties stored in the object are also updated
  2392. self.object_changed.emit(obj)
  2393. obj.build_ui()
  2394. current = self.collection.get_active()
  2395. if current is not None:
  2396. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2397. if not isinstance(current, FlatCAMGeometry):
  2398. current.to_form()
  2399. self.plot_all()
  2400. self.inform.emit("[success]Converted units to %s" % self.options["units"])
  2401. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2402. self.set_screen_units(self.options["units"])
  2403. else:
  2404. # Undo toggling
  2405. self.toggle_units_ignore = True
  2406. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2407. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2408. else:
  2409. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2410. self.toggle_units_ignore = False
  2411. self.inform.emit("[WARNING_NOTCL]Units conversion cancelled.")
  2412. self.options_read_form()
  2413. def on_toggle_units_click(self):
  2414. if self.options["units"] == 'MM':
  2415. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2416. else:
  2417. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2418. self.on_toggle_units()
  2419. def on_language_apply(self):
  2420. self.report_usage("on_language_apply()")
  2421. # TODO: apply the language
  2422. # app restart section
  2423. pass
  2424. def on_fullscreen(self):
  2425. self.report_usage("on_fullscreen()")
  2426. if self.toggle_fscreen is False:
  2427. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2428. tb.setVisible(False)
  2429. self.ui.splitter_left.setVisible(False)
  2430. self.toggle_fscreen = True
  2431. else:
  2432. self.restore_toolbar_view()
  2433. self.ui.splitter_left.setVisible(True)
  2434. self.toggle_fscreen = False
  2435. def on_toggle_plotarea(self):
  2436. self.report_usage("on_toggle_plotarea()")
  2437. try:
  2438. name = self.ui.plot_tab_area.widget(0).objectName()
  2439. except AttributeError:
  2440. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2441. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2442. self.ui.plot_tab_area.protectTab(0)
  2443. return
  2444. if name != 'plotarea':
  2445. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2446. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2447. self.ui.plot_tab_area.protectTab(0)
  2448. else:
  2449. self.ui.plot_tab_area.closeTab(0)
  2450. def on_toggle_notebook(self):
  2451. if self.ui.splitter.sizes()[0] == 0:
  2452. self.ui.splitter.setSizes([1, 1])
  2453. else:
  2454. self.ui.splitter.setSizes([0, 1])
  2455. def on_toggle_axis(self):
  2456. self.report_usage("on_toggle_axis()")
  2457. if self.toggle_axis is False:
  2458. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2459. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2460. self.plotcanvas.redraw()
  2461. self.toggle_axis = True
  2462. else:
  2463. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2464. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2465. self.plotcanvas.redraw()
  2466. self.toggle_axis = False
  2467. def on_toggle_grid(self):
  2468. self.report_usage("on_toggle_grid()")
  2469. self.ui.grid_snap_btn.trigger()
  2470. def on_options_combo_change(self, sel):
  2471. """
  2472. Called when the combo box to choose between application defaults and
  2473. project option changes value. The corresponding variables are
  2474. copied to the UI.
  2475. :param sel: The option index that was chosen.
  2476. :return: None
  2477. """
  2478. # combo_sel = self.ui.notebook.combo_options.get_active()
  2479. App.log.debug("Options --> %s" % sel)
  2480. # form = [self.defaults_form, self.options_form][sel]
  2481. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2482. if sel == 0:
  2483. self.gen_form = self.general_defaults_form
  2484. self.ger_form = self.gerber_defaults_form
  2485. self.exc_form = self.excellon_defaults_form
  2486. self.geo_form = self.geometry_defaults_form
  2487. self.cnc_form = self.cncjob_defaults_form
  2488. self.tools_form = self.tools_defaults_form
  2489. elif sel == 1:
  2490. self.gen_form = self.general_options_form
  2491. self.ger_form = self.gerber_options_form
  2492. self.exc_form = self.excellon_options_form
  2493. self.geo_form = self.geometry_options_form
  2494. self.cnc_form = self.cncjob_options_form
  2495. self.tools_form = self.tools_options_form
  2496. else:
  2497. return
  2498. try:
  2499. self.ui.general_scroll_area.takeWidget()
  2500. except:
  2501. self.log.debug("Nothing to remove")
  2502. self.ui.general_scroll_area.setWidget(self.gen_form)
  2503. self.gen_form.show()
  2504. try:
  2505. self.ui.gerber_scroll_area.takeWidget()
  2506. except:
  2507. self.log.debug("Nothing to remove")
  2508. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2509. self.ger_form.show()
  2510. try:
  2511. self.ui.excellon_scroll_area.takeWidget()
  2512. except:
  2513. self.log.debug("Nothing to remove")
  2514. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2515. self.exc_form.show()
  2516. try:
  2517. self.ui.geometry_scroll_area.takeWidget()
  2518. except:
  2519. self.log.debug("Nothing to remove")
  2520. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2521. self.geo_form.show()
  2522. try:
  2523. self.ui.cncjob_scroll_area.takeWidget()
  2524. except:
  2525. self.log.debug("Nothing to remove")
  2526. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2527. self.cnc_form.show()
  2528. try:
  2529. self.ui.tools_scroll_area.takeWidget()
  2530. except:
  2531. self.log.debug("Nothing to remove")
  2532. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2533. self.tools_form.show()
  2534. self.log.debug("Finished GUI form initialization.")
  2535. # self.options2form()
  2536. def on_excellon_defaults_button(self):
  2537. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2538. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2539. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2540. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2541. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2542. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2543. log.debug("Excellon app defaults loaded ...")
  2544. def on_excellon_options_button(self):
  2545. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2546. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2547. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2548. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2549. self.options_form_fields["excellon_zeros"].set_value('L')
  2550. self.options_form_fields["excellon_units"].set_value('INCH')
  2551. log.debug("Excellon options defaults loaded ...")
  2552. # Setting plot colors handlers
  2553. def on_pf_color_entry(self):
  2554. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2555. self.defaults['global_plot_fill'][7:9]
  2556. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2557. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2558. def on_pf_color_button(self):
  2559. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2560. c_dialog = QtWidgets.QColorDialog()
  2561. plot_fill_color = c_dialog.getColor(initial=current_color)
  2562. if plot_fill_color.isValid() is False:
  2563. return
  2564. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2565. "background-color:%s" % str(plot_fill_color.name()))
  2566. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2567. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2568. self.defaults['global_plot_fill'] = new_val
  2569. def on_pf_color_spinner(self):
  2570. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2571. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2572. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2573. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2574. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2575. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2576. def on_pf_color_slider(self):
  2577. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2578. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2579. def on_pl_color_entry(self):
  2580. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2581. self.defaults['global_plot_line'][7:9]
  2582. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2583. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2584. def on_pl_color_button(self):
  2585. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2586. # print(current_color)
  2587. c_dialog = QtWidgets.QColorDialog()
  2588. plot_line_color = c_dialog.getColor(initial=current_color)
  2589. if plot_line_color.isValid() is False:
  2590. return
  2591. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2592. "background-color:%s" % str(plot_line_color.name()))
  2593. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2594. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2595. self.defaults['global_plot_line'] = new_val_line
  2596. # Setting selection colors (left - right) handlers
  2597. def on_sf_color_entry(self):
  2598. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2599. self.defaults['global_sel_fill'][7:9]
  2600. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2601. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2602. def on_sf_color_button(self):
  2603. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2604. c_dialog = QtWidgets.QColorDialog()
  2605. plot_fill_color = c_dialog.getColor(initial=current_color)
  2606. if plot_fill_color.isValid() is False:
  2607. return
  2608. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2609. "background-color:%s" % str(plot_fill_color.name()))
  2610. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2611. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2612. self.defaults['global_sel_fill'] = new_val
  2613. def on_sf_color_spinner(self):
  2614. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2615. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2616. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2617. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2618. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2619. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2620. def on_sf_color_slider(self):
  2621. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2622. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2623. def on_sl_color_entry(self):
  2624. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2625. self.defaults['global_sel_line'][7:9]
  2626. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2627. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2628. def on_sl_color_button(self):
  2629. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2630. c_dialog = QtWidgets.QColorDialog()
  2631. plot_line_color = c_dialog.getColor(initial=current_color)
  2632. if plot_line_color.isValid() is False:
  2633. return
  2634. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2635. "background-color:%s" % str(plot_line_color.name()))
  2636. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2637. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2638. self.defaults['global_sel_line'] = new_val_line
  2639. # Setting selection colors (right - left) handlers
  2640. def on_alt_sf_color_entry(self):
  2641. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2642. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2643. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2644. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2645. def on_alt_sf_color_button(self):
  2646. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2647. c_dialog = QtWidgets.QColorDialog()
  2648. plot_fill_color = c_dialog.getColor(initial=current_color)
  2649. if plot_fill_color.isValid() is False:
  2650. return
  2651. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2652. "background-color:%s" % str(plot_fill_color.name()))
  2653. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2654. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2655. self.defaults['global_alt_sel_fill'] = new_val
  2656. def on_alt_sf_color_spinner(self):
  2657. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2658. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2659. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2660. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2661. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2662. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2663. def on_alt_sf_color_slider(self):
  2664. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2665. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2666. def on_alt_sl_color_entry(self):
  2667. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2668. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2669. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2670. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2671. def on_alt_sl_color_button(self):
  2672. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2673. c_dialog = QtWidgets.QColorDialog()
  2674. plot_line_color = c_dialog.getColor(initial=current_color)
  2675. if plot_line_color.isValid() is False:
  2676. return
  2677. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2678. "background-color:%s" % str(plot_line_color.name()))
  2679. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2680. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2681. self.defaults['global_alt_sel_line'] = new_val_line
  2682. # Setting Editor colors
  2683. def on_draw_color_entry(self):
  2684. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2685. .draw_color_entry.get_value()
  2686. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2687. "background-color:%s" % str(self.defaults['global_draw_color']))
  2688. def on_draw_color_button(self):
  2689. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2690. c_dialog = QtWidgets.QColorDialog()
  2691. draw_color = c_dialog.getColor(initial=current_color)
  2692. if draw_color.isValid() is False:
  2693. return
  2694. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2695. "background-color:%s" % str(draw_color.name()))
  2696. new_val = str(draw_color.name())
  2697. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2698. self.defaults['global_draw_color'] = new_val
  2699. def on_sel_draw_color_entry(self):
  2700. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2701. .sel_draw_color_entry.get_value()
  2702. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2703. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2704. def on_sel_draw_color_button(self):
  2705. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2706. c_dialog = QtWidgets.QColorDialog()
  2707. sel_draw_color = c_dialog.getColor(initial=current_color)
  2708. if sel_draw_color.isValid() is False:
  2709. return
  2710. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2711. "background-color:%s" % str(sel_draw_color.name()))
  2712. new_val_sel = str(sel_draw_color.name())
  2713. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2714. self.defaults['global_sel_draw_color'] = new_val_sel
  2715. def on_deselect_all(self):
  2716. self.collection.set_all_inactive()
  2717. self.delete_selection_shape()
  2718. def on_workspace_modified(self):
  2719. self.save_defaults(silent=True)
  2720. self.plotcanvas.draw_workspace()
  2721. def on_workspace(self):
  2722. self.report_usage("on_workspace()")
  2723. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2724. self.plotcanvas.restore_workspace()
  2725. else:
  2726. self.plotcanvas.delete_workspace()
  2727. self.save_defaults(silent=True)
  2728. def on_workspace_menu(self):
  2729. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2730. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2731. else:
  2732. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2733. self.on_workspace()
  2734. def on_layout(self):
  2735. self.report_usage("on_layout()")
  2736. current_layout= self.general_defaults_form.general_gui_group.layout_combo.get_value().lower()
  2737. settings = QSettings("Open Source", "FlatCAM")
  2738. settings.setValue('layout', current_layout)
  2739. # This will write the setting to the platform specific storage.
  2740. del settings
  2741. # first remove the toolbars:
  2742. self.ui.removeToolBar(self.ui.toolbarfile)
  2743. self.ui.removeToolBar(self.ui.toolbargeo)
  2744. self.ui.removeToolBar(self.ui.toolbarview)
  2745. self.ui.removeToolBar(self.ui.toolbartools)
  2746. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  2747. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  2748. self.ui.removeToolBar(self.ui.snap_toolbar)
  2749. if current_layout == 'standard':
  2750. ### TOOLBAR INSTALLATION ###
  2751. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2752. self.ui.toolbarfile.setObjectName('File_TB')
  2753. self.ui.addToolBar(self.ui.toolbarfile)
  2754. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2755. self.ui.toolbargeo.setObjectName('Edit_TB')
  2756. self.ui.addToolBar(self.ui.toolbargeo)
  2757. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2758. self.ui.toolbarview.setObjectName('View_TB')
  2759. self.ui.addToolBar(self.ui.toolbarview)
  2760. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2761. self.ui.toolbartools.setObjectName('Tools_TB')
  2762. self.ui.addToolBar(self.ui.toolbartools)
  2763. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2764. self.ui.exc_edit_toolbar.setVisible(False)
  2765. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2766. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  2767. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2768. self.ui.geo_edit_toolbar.setVisible(False)
  2769. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2770. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  2771. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2772. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2773. # self.ui.snap_toolbar.setMaximumHeight(30)
  2774. self.ui.addToolBar(self.ui.snap_toolbar)
  2775. self.ui.corner_snap_btn.setVisible(False)
  2776. self.ui.snap_magnet.setVisible(False)
  2777. elif current_layout == 'compact':
  2778. ### TOOLBAR INSTALLATION ###
  2779. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2780. self.ui.toolbarfile.setObjectName('File_TB')
  2781. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  2782. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2783. self.ui.toolbargeo.setObjectName('Edit_TB')
  2784. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  2785. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2786. self.ui.toolbarview.setObjectName('View_TB')
  2787. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  2788. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2789. self.ui.toolbartools.setObjectName('Tools_TB')
  2790. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  2791. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2792. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2793. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.exc_edit_toolbar)
  2794. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2795. self.ui.geo_edit_toolbar.setVisible(False)
  2796. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2797. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  2798. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2799. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2800. self.ui.snap_toolbar.setMaximumHeight(30)
  2801. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  2802. self.ui.corner_snap_btn.setVisible(True)
  2803. self.ui.snap_magnet.setVisible(True)
  2804. self.ui.populate_toolbars()
  2805. self.ui.grid_snap_btn.setChecked(True)
  2806. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  2807. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  2808. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  2809. self.ui.grid_gap_link_cb.setChecked(True)
  2810. def on_save_button(self):
  2811. self.save_defaults(silent=False)
  2812. # load the defaults so they are updated into the app
  2813. self.load_defaults(filename='current_defaults')
  2814. # Re-fresh project options
  2815. self.on_options_app2project()
  2816. def handleOpen(self):
  2817. self.report_usage("handleOpen()")
  2818. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2819. "All Files (*.*)"
  2820. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2821. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2822. if path:
  2823. file = QtCore.QFile(path)
  2824. if file.open(QtCore.QIODevice.ReadOnly):
  2825. stream = QtCore.QTextStream(file)
  2826. self.gcode_edited = stream.readAll()
  2827. self.ui.code_editor.setPlainText(self.gcode_edited)
  2828. file.close()
  2829. def handlePrint(self):
  2830. self.report_usage("handlePrint()")
  2831. dialog = QtPrintSupport.QPrintDialog()
  2832. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2833. self.ui.code_editor.document().print_(dialog.printer())
  2834. def handlePreview(self):
  2835. self.report_usage("handlePreview()")
  2836. dialog = QtPrintSupport.QPrintPreviewDialog()
  2837. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2838. dialog.exec_()
  2839. def handleTextChanged(self):
  2840. self.report_usage("handleTextChanged()")
  2841. # enable = not self.ui.code_editor.document().isEmpty()
  2842. # self.ui.buttonPrint.setEnabled(enable)
  2843. # self.ui.buttonPreview.setEnabled(enable)
  2844. pass
  2845. def handleSaveGCode(self):
  2846. self.report_usage("handleSaveGCode()")
  2847. obj_name = self.collection.get_active().options['name']
  2848. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2849. "All Files (*.*)"
  2850. try:
  2851. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2852. caption="Export G-Code ...",
  2853. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  2854. filter=_filter_
  2855. )[0])
  2856. except TypeError:
  2857. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2858. if filename == "":
  2859. self.inform.emit("[WARNING_NOTCL]Export CNC Code cancelled.")
  2860. return
  2861. else:
  2862. try:
  2863. my_gcode = self.ui.code_editor.toPlainText()
  2864. with open(filename, 'w') as f:
  2865. for line in my_gcode:
  2866. f.write(line)
  2867. except FileNotFoundError:
  2868. self.inform.emit("[WARNING] No such file or directory")
  2869. return
  2870. # Just for adding it to the recent files list.
  2871. self.file_opened.emit("cncjob", filename)
  2872. self.file_saved.emit("cncjob", filename)
  2873. self.inform.emit("Saved to: " + filename)
  2874. def handleFindGCode(self):
  2875. self.report_usage("handleFindGCode()")
  2876. flags = QtGui.QTextDocument.FindCaseSensitively
  2877. text_to_be_found = self.ui.entryFind.get_value()
  2878. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2879. if r is False:
  2880. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2881. def handleReplaceGCode(self):
  2882. self.report_usage("handleReplaceGCode()")
  2883. old = self.ui.entryFind.get_value()
  2884. new = self.ui.entryReplace.get_value()
  2885. if self.ui.sel_all_cb.isChecked():
  2886. while True:
  2887. cursor = self.ui.code_editor.textCursor()
  2888. cursor.beginEditBlock()
  2889. flags = QtGui.QTextDocument.FindCaseSensitively
  2890. # self.ui.editor is the QPlainTextEdit
  2891. r = self.ui.code_editor.find(str(old), flags)
  2892. if r:
  2893. qc = self.ui.code_editor.textCursor()
  2894. if qc.hasSelection():
  2895. qc.insertText(new)
  2896. else:
  2897. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2898. break
  2899. # Mark end of undo block
  2900. cursor.endEditBlock()
  2901. else:
  2902. cursor = self.ui.code_editor.textCursor()
  2903. cursor.beginEditBlock()
  2904. qc = self.ui.code_editor.textCursor()
  2905. if qc.hasSelection():
  2906. qc.insertText(new)
  2907. # Mark end of undo block
  2908. cursor.endEditBlock()
  2909. def on_tool_add_keypress(self):
  2910. ## Current application units in Upper Case
  2911. self.units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2912. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2913. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2914. if notebook_widget_name == 'selected_tab':
  2915. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2916. tool_add_popup = FCInputDialog(title="New Tool ...",
  2917. text='Enter a Tool Diameter:',
  2918. min=0.0000, max=99.9999, decimals=4)
  2919. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2920. val, ok = tool_add_popup.get_value()
  2921. if ok:
  2922. if float(val) == 0:
  2923. self.inform.emit(
  2924. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2925. return
  2926. self.collection.get_active().on_tool_add(dia=float(val))
  2927. else:
  2928. self.inform.emit(
  2929. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2930. # work only if the notebook tab on focus is the Tools_Tab
  2931. if notebook_widget_name == 'tool_tab':
  2932. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2933. # and only if the tool is NCC Tool
  2934. if tool_widget == self.ncclear_tool.toolName:
  2935. tool_add_popup = FCInputDialog(title="New Tool ...",
  2936. text='Enter a Tool Diameter:',
  2937. min=0.0000, max=99.9999, decimals=4)
  2938. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2939. val, ok = tool_add_popup.get_value()
  2940. if ok:
  2941. if float(val) == 0:
  2942. self.inform.emit(
  2943. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2944. return
  2945. self.ncclear_tool.on_tool_add(dia=float(val))
  2946. else:
  2947. self.inform.emit(
  2948. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2949. # and only if the tool is Paint Area Tool
  2950. elif tool_widget == self.paint_tool.toolName:
  2951. tool_add_popup = FCInputDialog(title="New Tool ...",
  2952. text='Enter a Tool Diameter:',
  2953. min=0.0000, max=99.9999, decimals=4)
  2954. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2955. val, ok = tool_add_popup.get_value()
  2956. if ok:
  2957. if float(val) == 0:
  2958. self.inform.emit(
  2959. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2960. return
  2961. self.paint_tool.on_tool_add(dia=float(val))
  2962. else:
  2963. self.inform.emit(
  2964. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2965. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  2966. # See description bellow.
  2967. def on_delete_keypress(self):
  2968. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2969. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2970. if notebook_widget_name == 'selected_tab':
  2971. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2972. self.collection.get_active().on_tool_delete()
  2973. # work only if the notebook tab on focus is the Tools_Tab
  2974. elif notebook_widget_name == 'tool_tab':
  2975. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2976. # and only if the tool is NCC Tool
  2977. if tool_widget == self.ncclear_tool.toolName:
  2978. self.ncclear_tool.on_tool_delete()
  2979. # and only if the tool is Paint Tool
  2980. elif tool_widget == self.paint_tool.toolName:
  2981. self.paint_tool.on_tool_delete()
  2982. else:
  2983. self.on_delete()
  2984. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  2985. # some screens you have to be careful where you hover with your mouse.
  2986. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  2987. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  2988. # Complicated, I know :)
  2989. def on_delete(self):
  2990. """
  2991. Delete the currently selected FlatCAMObjs.
  2992. :return: None
  2993. """
  2994. self.report_usage("on_delete()")
  2995. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2996. # a geometry object before we update it.
  2997. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2998. if self.collection.get_active():
  2999. self.log.debug("on_delete()")
  3000. self.report_usage("on_delete")
  3001. while (self.collection.get_active()):
  3002. self.delete_first_selected()
  3003. self.inform.emit("Object(s) deleted ...")
  3004. # make sure that the selection shape is deleted, too
  3005. self.delete_selection_shape()
  3006. else:
  3007. self.inform.emit("Failed. No object(s) selected...")
  3008. else:
  3009. self.inform.emit("Save the work in Editor and try again ...")
  3010. def on_set_origin(self):
  3011. """
  3012. Set the origin to the left mouse click position
  3013. :return: None
  3014. """
  3015. #display the message for the user
  3016. #and ask him to click on the desired position
  3017. self.report_usage("on_set_origin()")
  3018. self.inform.emit('Click to set the origin ...')
  3019. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3020. def on_jump_to(self):
  3021. """
  3022. Jump to a location by setting the mouse cursor location
  3023. :return:
  3024. """
  3025. self.report_usage("on_jump_to()")
  3026. dia_box = Dialog_box(title="Jump to ...",
  3027. label="Enter the coordinates in format X,Y:",
  3028. icon=QtGui.QIcon('share/jump_to16.png'))
  3029. if dia_box.ok is True:
  3030. try:
  3031. location = eval(dia_box.location)
  3032. if not isinstance(location, tuple):
  3033. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  3034. return
  3035. except:
  3036. return
  3037. else:
  3038. return
  3039. self.plotcanvas.fit_center(loc=location)
  3040. cursor = QtGui.QCursor()
  3041. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3042. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3043. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3044. self.inform.emit("Done.")
  3045. def on_copy_object(self):
  3046. self.report_usage("on_copy_object()")
  3047. def initialize(obj_init, app):
  3048. obj_init.solid_geometry = obj.solid_geometry
  3049. try:
  3050. if obj.tools:
  3051. obj_init.tools = obj.tools
  3052. except Exception as e:
  3053. log.debug("on_copy_object() --> %s" % str(e))
  3054. def initialize_excellon(obj_init, app):
  3055. obj_init.tools = obj.tools
  3056. # drills are offset, so they need to be deep copied
  3057. obj_init.drills = deepcopy(obj.drills)
  3058. # slots are offset, so they need to be deep copied
  3059. obj_init.slots = deepcopy(obj.slots)
  3060. obj_init.create_geometry()
  3061. for obj in self.collection.get_selected():
  3062. obj_name = obj.options["name"]
  3063. try:
  3064. if isinstance(obj, FlatCAMExcellon):
  3065. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3066. elif isinstance(obj,FlatCAMGerber):
  3067. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3068. elif isinstance(obj,FlatCAMGeometry):
  3069. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3070. except Exception as e:
  3071. return "Operation failed: %s" % str(e)
  3072. def on_copy_object2(self, custom_name):
  3073. def initialize_geometry(obj_init, app):
  3074. obj_init.solid_geometry = obj.solid_geometry
  3075. try:
  3076. if obj.tools:
  3077. obj_init.tools = obj.tools
  3078. except Exception as e:
  3079. log.debug("on_copy_object2() --> %s" % str(e))
  3080. def initialize_gerber(obj_init, app):
  3081. obj_init.solid_geometry = obj.solid_geometry
  3082. obj_init.apertures = deepcopy(obj.apertures)
  3083. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3084. def initialize_excellon(obj_init, app):
  3085. obj_init.tools = obj.tools
  3086. # drills are offset, so they need to be deep copied
  3087. obj_init.drills = deepcopy(obj.drills)
  3088. # slots are offset, so they need to be deep copied
  3089. obj_init.slots = deepcopy(obj.slots)
  3090. obj_init.create_geometry()
  3091. for obj in self.collection.get_selected():
  3092. obj_name = obj.options["name"]
  3093. try:
  3094. if isinstance(obj, FlatCAMExcellon):
  3095. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3096. elif isinstance(obj,FlatCAMGerber):
  3097. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3098. elif isinstance(obj,FlatCAMGeometry):
  3099. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3100. except Exception as e:
  3101. return "Operation failed: %s" % str(e)
  3102. def on_rename_object(self, text):
  3103. self.report_usage("on_rename_object()")
  3104. named_obj = self.collection.get_active()
  3105. for obj in named_obj:
  3106. if obj is list:
  3107. self.on_rename_object(text)
  3108. else:
  3109. try:
  3110. obj.options['name'] = text
  3111. except:
  3112. log.warning("Could not rename the object in the list")
  3113. def on_copy_object_as_geometry(self):
  3114. self.report_usage("on_copy_object_as_geometry()")
  3115. def initialize(obj_init, app):
  3116. obj_init.solid_geometry = obj.solid_geometry
  3117. if obj.tools:
  3118. obj_init.tools = obj.tools
  3119. def initialize_excellon(obj, app):
  3120. objs = self.collection.get_selected()
  3121. FlatCAMGeometry.merge(objs, obj)
  3122. for obj in self.collection.get_selected():
  3123. obj_name = obj.options["name"]
  3124. try:
  3125. if isinstance(obj, FlatCAMExcellon):
  3126. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3127. else:
  3128. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3129. except Exception as e:
  3130. return "Operation failed: %s" % str(e)
  3131. def on_set_zero_click(self, event):
  3132. #this function will be available only for mouse left click
  3133. pos =[]
  3134. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3135. if event.button == 1:
  3136. if self.grid_status() == True:
  3137. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3138. else:
  3139. pos = pos_canvas
  3140. x = 0 - pos[0]
  3141. y = 0 - pos[1]
  3142. for obj in self.collection.get_list():
  3143. obj.offset((x,y))
  3144. self.object_changed.emit(obj)
  3145. # obj.plot()
  3146. self.plot_all(zoom=False)
  3147. self.inform.emit('[success] Origin set ...')
  3148. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3149. def on_selectall(self):
  3150. self.report_usage("on_selectall()")
  3151. # delete the possible selection box around a possible selected object
  3152. self.delete_selection_shape()
  3153. for name in self.collection.get_names():
  3154. self.collection.set_active(name)
  3155. curr_sel_obj = self.collection.get_by_name(name)
  3156. # create the selection box around the selected object
  3157. self.draw_selection_shape(curr_sel_obj)
  3158. def on_preferences(self):
  3159. # add the tab if it was closed
  3160. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  3161. # delete the absolute and relative position and messages in the infobar
  3162. self.ui.position_label.setText("")
  3163. self.ui.rel_position_label.setText("")
  3164. # Switch plot_area to preferences page
  3165. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3166. self.ui.show()
  3167. def on_flipy(self):
  3168. self.report_usage("on_flipy()")
  3169. obj_list = self.collection.get_selected()
  3170. xminlist = []
  3171. yminlist = []
  3172. xmaxlist = []
  3173. ymaxlist = []
  3174. if not obj_list:
  3175. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on Y axis.")
  3176. else:
  3177. try:
  3178. # first get a bounding box to fit all
  3179. for obj in obj_list:
  3180. xmin, ymin, xmax, ymax = obj.bounds()
  3181. xminlist.append(xmin)
  3182. yminlist.append(ymin)
  3183. xmaxlist.append(xmax)
  3184. ymaxlist.append(ymax)
  3185. # get the minimum x,y and maximum x,y for all objects selected
  3186. xminimal = min(xminlist)
  3187. yminimal = min(yminlist)
  3188. xmaximal = max(xmaxlist)
  3189. ymaximal = max(ymaxlist)
  3190. px = 0.5 * (xminimal + xmaximal)
  3191. py = 0.5 * (yminimal + ymaximal)
  3192. # execute mirroring
  3193. for obj in obj_list:
  3194. obj.mirror('X', [px, py])
  3195. obj.plot()
  3196. self.object_changed.emit(obj)
  3197. except Exception as e:
  3198. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3199. return
  3200. def on_flipx(self):
  3201. self.report_usage("on_flipx()")
  3202. obj_list = self.collection.get_selected()
  3203. xminlist = []
  3204. yminlist = []
  3205. xmaxlist = []
  3206. ymaxlist = []
  3207. if not obj_list:
  3208. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on X axis.")
  3209. else:
  3210. try:
  3211. # first get a bounding box to fit all
  3212. for obj in obj_list:
  3213. xmin, ymin, xmax, ymax = obj.bounds()
  3214. xminlist.append(xmin)
  3215. yminlist.append(ymin)
  3216. xmaxlist.append(xmax)
  3217. ymaxlist.append(ymax)
  3218. # get the minimum x,y and maximum x,y for all objects selected
  3219. xminimal = min(xminlist)
  3220. yminimal = min(yminlist)
  3221. xmaximal = max(xmaxlist)
  3222. ymaximal = max(ymaxlist)
  3223. px = 0.5 * (xminimal + xmaximal)
  3224. py = 0.5 * (yminimal + ymaximal)
  3225. # execute mirroring
  3226. for obj in obj_list:
  3227. obj.mirror('Y', [px, py])
  3228. obj.plot()
  3229. self.object_changed.emit(obj)
  3230. except Exception as e:
  3231. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3232. return
  3233. def on_rotate(self, silent=False, preset=None):
  3234. self.report_usage("on_rotate()")
  3235. obj_list = self.collection.get_selected()
  3236. xminlist = []
  3237. yminlist = []
  3238. xmaxlist = []
  3239. ymaxlist = []
  3240. if not obj_list:
  3241. self.inform.emit("[WARNING_NOTCL] No object selected to Rotate.")
  3242. else:
  3243. if silent is False:
  3244. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3245. min=-360, max=360, decimals=3)
  3246. num, ok = rotatebox.get_value()
  3247. else:
  3248. num = preset
  3249. ok = True
  3250. if ok:
  3251. try:
  3252. # first get a bounding box to fit all
  3253. for obj in obj_list:
  3254. xmin, ymin, xmax, ymax = obj.bounds()
  3255. xminlist.append(xmin)
  3256. yminlist.append(ymin)
  3257. xmaxlist.append(xmax)
  3258. ymaxlist.append(ymax)
  3259. # get the minimum x,y and maximum x,y for all objects selected
  3260. xminimal = min(xminlist)
  3261. yminimal = min(yminlist)
  3262. xmaximal = max(xmaxlist)
  3263. ymaximal = max(ymaxlist)
  3264. px = 0.5 * (xminimal + xmaximal)
  3265. py = 0.5 * (yminimal + ymaximal)
  3266. for sel_obj in obj_list:
  3267. sel_obj.rotate(-num, point=(px, py))
  3268. sel_obj.plot()
  3269. self.object_changed.emit(sel_obj)
  3270. except Exception as e:
  3271. self.inform.emit("[ERROR_NOTCL] Due of %s, rotation movement was not executed." % str(e))
  3272. return
  3273. def on_skewx(self):
  3274. self.report_usage("on_skewx()")
  3275. obj_list = self.collection.get_selected()
  3276. xminlist = []
  3277. yminlist = []
  3278. if not obj_list:
  3279. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on X axis.")
  3280. else:
  3281. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3282. min=-360, max=360, decimals=3)
  3283. num, ok = skewxbox.get_value()
  3284. if ok:
  3285. # first get a bounding box to fit all
  3286. for obj in obj_list:
  3287. xmin, ymin, xmax, ymax = obj.bounds()
  3288. xminlist.append(xmin)
  3289. yminlist.append(ymin)
  3290. # get the minimum x,y and maximum x,y for all objects selected
  3291. xminimal = min(xminlist)
  3292. yminimal = min(yminlist)
  3293. for obj in obj_list:
  3294. obj.skew(num, 0, point=(xminimal, yminimal))
  3295. obj.plot()
  3296. self.object_changed.emit(obj)
  3297. def on_skewy(self):
  3298. self.report_usage("on_skewy()")
  3299. obj_list = self.collection.get_selected()
  3300. xminlist = []
  3301. yminlist = []
  3302. if not obj_list:
  3303. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis.")
  3304. else:
  3305. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3306. min=-360, max=360, decimals=3)
  3307. num, ok = skewybox.get_value()
  3308. if ok:
  3309. # first get a bounding box to fit all
  3310. for obj in obj_list:
  3311. xmin, ymin, xmax, ymax = obj.bounds()
  3312. xminlist.append(xmin)
  3313. yminlist.append(ymin)
  3314. # get the minimum x,y and maximum x,y for all objects selected
  3315. xminimal = min(xminlist)
  3316. yminimal = min(yminlist)
  3317. for obj in obj_list:
  3318. obj.skew(0, num, point=(xminimal, yminimal))
  3319. obj.plot()
  3320. self.object_changed.emit(obj)
  3321. def delete_first_selected(self):
  3322. # Keep this for later
  3323. try:
  3324. name = self.collection.get_active().options["name"]
  3325. except AttributeError:
  3326. self.log.debug("Nothing selected for deletion")
  3327. return
  3328. # Remove plot
  3329. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3330. # self.plotcanvas.auto_adjust_axes()
  3331. # Clear form
  3332. self.setup_component_editor()
  3333. # Remove from dictionary
  3334. self.collection.delete_active()
  3335. self.inform.emit("Object deleted: %s" % name)
  3336. def on_plots_updated(self):
  3337. """
  3338. Callback used to report when the plots have changed.
  3339. Adjust axes and zooms to fit.
  3340. :return: None
  3341. """
  3342. # self.plotcanvas.auto_adjust_axes()
  3343. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3344. self.on_zoom_fit(None)
  3345. # TODO: Rework toolbar 'clear', 'replot' functions
  3346. def on_toolbar_replot(self):
  3347. """
  3348. Callback for toolbar button. Re-plots all objects.
  3349. :return: None
  3350. """
  3351. self.report_usage("on_toolbar_replot")
  3352. self.log.debug("on_toolbar_replot()")
  3353. try:
  3354. self.collection.get_active().read_form()
  3355. except AttributeError:
  3356. self.log.debug("on_toolbar_replot(): AttributeError")
  3357. pass
  3358. self.plot_all()
  3359. def on_row_activated(self, index):
  3360. if index.isValid():
  3361. if index.internalPointer().parent_item != self.collection.root_item:
  3362. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3363. def grid_status(self):
  3364. if self.ui.grid_snap_btn.isChecked():
  3365. return 1
  3366. else:
  3367. return 0
  3368. def populate_cmenu_grids(self):
  3369. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3370. self.ui.cmenu_gridmenu.clear()
  3371. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  3372. for grid in sorted_list:
  3373. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  3374. action.triggered.connect(self.set_grid)
  3375. self.ui.cmenu_gridmenu.addSeparator()
  3376. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  3377. grid_add.triggered.connect(self.on_grid_add)
  3378. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  3379. grid_delete.triggered.connect(self.on_grid_delete)
  3380. def set_grid(self):
  3381. self.ui.grid_gap_x_entry.setText(self.sender().text())
  3382. self.ui.grid_gap_y_entry.setText(self.sender().text())
  3383. def on_grid_add(self):
  3384. ## Current application units in lower Case
  3385. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3386. grid_add_popup = FCInputDialog(title="New Grid ...",
  3387. text='Enter a Grid VAlue:',
  3388. min=0.0000, max=99.9999, decimals=4)
  3389. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  3390. val, ok = grid_add_popup.get_value()
  3391. if ok:
  3392. if float(val) == 0:
  3393. self.inform.emit(
  3394. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3395. return
  3396. else:
  3397. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  3398. self.defaults["global_grid_context_menu"][str(units)].append(val)
  3399. self.inform.emit(
  3400. "[success] New Grid added ...")
  3401. else:
  3402. self.inform.emit(
  3403. "[WARNING_NOTCL] Grid already exists ...")
  3404. else:
  3405. self.inform.emit(
  3406. "[WARNING_NOTCL] Adding New Grid cancelled ...")
  3407. def on_grid_delete(self):
  3408. ## Current application units in lower Case
  3409. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3410. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  3411. text='Enter a Grid Value:',
  3412. min=0.0000, max=99.9999, decimals=4)
  3413. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  3414. val, ok = grid_del_popup.get_value()
  3415. if ok:
  3416. if float(val) == 0:
  3417. self.inform.emit(
  3418. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3419. return
  3420. else:
  3421. try:
  3422. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  3423. except ValueError:
  3424. self.inform.emit(
  3425. "[ERROR_NOTCL] Grid Value does not exist ...")
  3426. return
  3427. self.inform.emit(
  3428. "[success] Grid Value deleted ...")
  3429. else:
  3430. self.inform.emit(
  3431. "[WARNING_NOTCL] Delete Grid value cancelled ...")
  3432. def on_shortcut_list(self):
  3433. self.report_usage("on_shortcut_list()")
  3434. # add the tab if it was closed
  3435. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3436. # delete the absolute and relative position and messages in the infobar
  3437. self.ui.position_label.setText("")
  3438. self.ui.rel_position_label.setText("")
  3439. # Switch plot_area to preferences page
  3440. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3441. self.ui.show()
  3442. def on_select_tab(self, name):
  3443. if name == 'project':
  3444. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3445. elif name == 'selected':
  3446. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3447. elif name == 'tool':
  3448. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3449. # if the splitter us hidden, display it
  3450. if self.ui.splitter.sizes()[0] == 0:
  3451. self.ui.splitter.setSizes([1, 1])
  3452. def on_copy_name(self):
  3453. self.report_usage("on_copy_name()")
  3454. obj = self.collection.get_active()
  3455. try:
  3456. name = obj.options["name"]
  3457. except AttributeError:
  3458. log.debug("on_copy_name() --> No object selected to copy it's name")
  3459. self.inform.emit("[WARNING_NOTCL]No object selected to copy it's name")
  3460. return
  3461. self.clipboard.setText(name)
  3462. self.inform.emit("Name copied on clipboard ...")
  3463. def on_mouse_click_over_plot(self, event):
  3464. """
  3465. Callback for the mouse click event over the plot. This event is generated
  3466. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3467. For details, see: http://matplotlib.org/users/event_handling.html
  3468. Default actions are:
  3469. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3470. :param event: Contains information about the event, like which button
  3471. was clicked, the pixel coordinates and the axes coordinates.
  3472. :return: None
  3473. """
  3474. self.pos = []
  3475. # So it can receive key presses
  3476. self.plotcanvas.vispy_canvas.native.setFocus()
  3477. # Set the mouse button for panning
  3478. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3479. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3480. if self.grid_status() == True:
  3481. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3482. self.app_cursor.enabled = True
  3483. else:
  3484. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3485. self.app_cursor.enabled = False
  3486. try:
  3487. # App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3488. # event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3489. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3490. if event.button == 1:
  3491. # Reset here the relative coordinates so there is a new reference on the click position
  3492. if self.rel_point1 is None:
  3493. self.rel_point1 = self.pos
  3494. else:
  3495. self.rel_point2 = copy(self.rel_point1)
  3496. self.rel_point1 = self.pos
  3497. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3498. if modifiers == QtCore.Qt.ShiftModifier:
  3499. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3500. return
  3501. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3502. # and if it's not selected then it will be selected
  3503. if modifiers == QtCore.Qt.ControlModifier:
  3504. # If there is no active command (self.command_active is None) then we check if we clicked on
  3505. # a object by checking the bounding limits against mouse click position
  3506. if self.command_active is None:
  3507. self.select_objects(key='CTRL')
  3508. else:
  3509. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3510. # checking the bounding limits against mouse click position
  3511. if self.command_active is None:
  3512. self.select_objects()
  3513. self.on_mouse_move_over_plot(event, origin_click=True)
  3514. except Exception as e:
  3515. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3516. def on_double_click_over_plot(self, event):
  3517. # make double click work only for the LMB
  3518. if event.button == 1:
  3519. if self.collection.get_selected():
  3520. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3521. # delete the selection shape(S) as it may be in the way
  3522. self.delete_selection_shape()
  3523. def on_mouse_move_over_plot(self, event, origin_click=None):
  3524. """
  3525. Callback for the mouse motion event over the plot. This event is generated
  3526. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3527. For details, see: http://matplotlib.org/users/event_handling.html
  3528. :param event: Contains information about the event.
  3529. :param origin_click
  3530. :return: None
  3531. """
  3532. # So it can receive key presses
  3533. self.plotcanvas.vispy_canvas.native.setFocus()
  3534. self.pos_jump = event.pos
  3535. if origin_click is True:
  3536. pass
  3537. else:
  3538. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3539. if event.button == 2:
  3540. self.panning_action = True
  3541. return
  3542. else:
  3543. self.panning_action = False
  3544. if self.rel_point1 is not None:
  3545. try: # May fail in case mouse not within axes
  3546. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3547. if self.grid_status():
  3548. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3549. self.app_cursor.enabled = True
  3550. # Update cursor
  3551. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3552. else:
  3553. pos = (pos_canvas[0], pos_canvas[1])
  3554. self.app_cursor.enabled = False
  3555. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3556. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3557. dx = pos[0] - self.rel_point1[0]
  3558. dy = pos[1] - self.rel_point1[1]
  3559. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3560. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3561. self.mouse = [pos[0], pos[1]]
  3562. # if the mouse is moved and the LMB is clicked then the action is a selection
  3563. if event.is_dragging == 1 and event.button == 1:
  3564. self.delete_selection_shape()
  3565. if dx < 0:
  3566. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3567. face_color=self.defaults['global_alt_sel_fill'])
  3568. self.selection_type = False
  3569. else:
  3570. self.draw_moving_selection_shape(self.pos, pos)
  3571. self.selection_type = True
  3572. # delete the status message on mouse move
  3573. # self.inform.emit("")
  3574. except:
  3575. self.ui.position_label.setText("")
  3576. self.ui.rel_position_label.setText("")
  3577. self.mouse = None
  3578. def on_mouse_click_release_over_plot(self, event):
  3579. """
  3580. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3581. and has been registered in ''self.__init__()''.
  3582. :param event: contains information about the event.
  3583. :return:
  3584. """
  3585. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3586. if self.grid_status():
  3587. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3588. else:
  3589. pos = (pos_canvas[0], pos_canvas[1])
  3590. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3591. # canvas menu
  3592. try:
  3593. if event.button == 2: # right click
  3594. if self.panning_action is True:
  3595. self.panning_action = False
  3596. else:
  3597. self.cursor = QtGui.QCursor()
  3598. self.populate_cmenu_grids()
  3599. self.ui.popMenu.popup(self.cursor.pos())
  3600. except Exception as e:
  3601. log.warning("Error: %s" % str(e))
  3602. return
  3603. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3604. # selection and then select a type of selection ("enclosing" or "touching")
  3605. try:
  3606. if event.button == 1: # left click
  3607. if self.selection_type is not None:
  3608. self.selection_area_handler(self.pos, pos, self.selection_type)
  3609. self.selection_type = None
  3610. except Exception as e:
  3611. log.warning("Error: %s" % str(e))
  3612. return
  3613. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3614. """
  3615. :param start_pos: mouse position when the selection LMB click was done
  3616. :param end_pos: mouse position when the left mouse button is released
  3617. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3618. :return:
  3619. """
  3620. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3621. self.delete_selection_shape()
  3622. for obj in self.collection.get_list():
  3623. try:
  3624. # select the object(s) only if it is enabled (plotted)
  3625. if obj.options['plot']:
  3626. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3627. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3628. if sel_type is True:
  3629. if poly_obj.within(poly_selection):
  3630. # create the selection box around the selected object
  3631. self.draw_selection_shape(obj)
  3632. self.collection.set_active(obj.options['name'])
  3633. else:
  3634. if poly_selection.intersects(poly_obj):
  3635. # create the selection box around the selected object
  3636. self.draw_selection_shape(obj)
  3637. self.collection.set_active(obj.options['name'])
  3638. except:
  3639. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3640. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3641. # In this case poly_obj creation (see above) will fail
  3642. pass
  3643. def select_objects(self, key=None):
  3644. # list where we store the overlapped objects under our mouse left click position
  3645. objects_under_the_click_list = []
  3646. # Populate the list with the overlapped objects on the click position
  3647. curr_x, curr_y = self.pos
  3648. for obj in self.all_objects_list:
  3649. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3650. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3651. if obj.options['name'] not in objects_under_the_click_list:
  3652. if obj.options['plot']:
  3653. # add objects to the objects_under_the_click list only if the object is plotted
  3654. # (active and not disabled)
  3655. objects_under_the_click_list.append(obj.options['name'])
  3656. try:
  3657. # If there is no element in the overlapped objects list then make everyone inactive
  3658. # because we selected "nothing"
  3659. if not objects_under_the_click_list:
  3660. self.collection.set_all_inactive()
  3661. # delete the possible selection box around a possible selected object
  3662. self.delete_selection_shape()
  3663. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3664. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3665. # delete any text in the status bar, implicitly the last object name that was selected
  3666. self.inform.emit("")
  3667. else:
  3668. # case when there is only an object under the click and we toggle it
  3669. if len(objects_under_the_click_list) == 1:
  3670. if self.collection.get_active() is None :
  3671. self.collection.set_active(objects_under_the_click_list[0])
  3672. # create the selection box around the selected object
  3673. curr_sel_obj = self.collection.get_active()
  3674. self.draw_selection_shape(curr_sel_obj)
  3675. # self.inform.emit('[selected] %s: %s selected' %
  3676. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3677. if curr_sel_obj.kind == 'gerber':
  3678. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3679. ('green', str(curr_sel_obj.options['name'])))
  3680. elif curr_sel_obj.kind == 'excellon':
  3681. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3682. ('brown', str(curr_sel_obj.options['name'])))
  3683. elif curr_sel_obj.kind == 'cncjob':
  3684. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3685. ('blue', str(curr_sel_obj.options['name'])))
  3686. elif curr_sel_obj.kind == 'geometry':
  3687. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3688. ('red', str(curr_sel_obj.options['name'])))
  3689. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3690. self.collection.set_all_inactive()
  3691. self.delete_selection_shape()
  3692. self.collection.set_active(objects_under_the_click_list[0])
  3693. # create the selection box around the selected object
  3694. curr_sel_obj = self.collection.get_active()
  3695. self.draw_selection_shape(curr_sel_obj)
  3696. # self.inform.emit('[selected] %s: %s selected' %
  3697. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3698. if curr_sel_obj.kind == 'gerber':
  3699. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3700. ('green', str(curr_sel_obj.options['name'])))
  3701. elif curr_sel_obj.kind == 'excellon':
  3702. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3703. ('brown', str(curr_sel_obj.options['name'])))
  3704. elif curr_sel_obj.kind == 'cncjob':
  3705. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3706. ('blue', str(curr_sel_obj.options['name'])))
  3707. elif curr_sel_obj.kind == 'geometry':
  3708. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3709. ('red', str(curr_sel_obj.options['name'])))
  3710. else:
  3711. self.collection.set_all_inactive()
  3712. self.delete_selection_shape()
  3713. self.inform.emit("")
  3714. else:
  3715. # If there is no selected object
  3716. # make active the first element of the overlapped objects list
  3717. if self.collection.get_active() is None:
  3718. self.collection.set_active(objects_under_the_click_list[0])
  3719. name_sel_obj = self.collection.get_active().options['name']
  3720. # In case that there is a selected object but it is not in the overlapped object list
  3721. # make that object inactive and activate the first element in the overlapped object list
  3722. if name_sel_obj not in objects_under_the_click_list:
  3723. self.collection.set_inactive(name_sel_obj)
  3724. name_sel_obj = objects_under_the_click_list[0]
  3725. self.collection.set_active(name_sel_obj)
  3726. else:
  3727. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3728. self.collection.set_all_inactive()
  3729. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  3730. len(objects_under_the_click_list)])
  3731. curr_sel_obj = self.collection.get_active()
  3732. # delete the possible selection box around a possible selected object
  3733. self.delete_selection_shape()
  3734. # create the selection box around the selected object
  3735. self.draw_selection_shape(curr_sel_obj)
  3736. # self.inform.emit('[selected] %s: %s selected' %
  3737. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3738. if curr_sel_obj.kind == 'gerber':
  3739. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3740. ('green', str(curr_sel_obj.options['name'])))
  3741. elif curr_sel_obj.kind == 'excellon':
  3742. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3743. ('brown', str(curr_sel_obj.options['name'])))
  3744. elif curr_sel_obj.kind == 'cncjob':
  3745. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3746. ('blue', str(curr_sel_obj.options['name'])))
  3747. elif curr_sel_obj.kind == 'geometry':
  3748. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3749. ('red', str(curr_sel_obj.options['name'])))
  3750. # for obj in self.collection.get_list():
  3751. # obj.plot()
  3752. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3753. # TODO: on selected objects change the object colors and do not draw the selection box
  3754. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3755. except Exception as e:
  3756. log.error("[ERROR] Something went bad. %s" % str(e))
  3757. return
  3758. def delete_selection_shape(self):
  3759. self.move_tool.sel_shapes.clear()
  3760. self.move_tool.sel_shapes.redraw()
  3761. def draw_selection_shape(self, sel_obj):
  3762. """
  3763. :param sel_obj: the object for which the selection shape must be drawn
  3764. :return:
  3765. """
  3766. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3767. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3768. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3769. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3770. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3771. #blue_t = Color('blue')
  3772. blue_t = Color(self.defaults['global_sel_fill'])
  3773. blue_t.alpha = 0.3
  3774. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3775. face_color=blue_t, update=True, layer=0, tolerance=None))
  3776. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3777. """
  3778. :param old_coords: old coordinates
  3779. :param coords: new coordinates
  3780. :return:
  3781. """
  3782. if 'color' in kwargs:
  3783. color = kwargs['color']
  3784. else:
  3785. color = self.defaults['global_sel_line']
  3786. if 'face_color' in kwargs:
  3787. face_color = kwargs['face_color']
  3788. else:
  3789. face_color = self.defaults['global_sel_fill']
  3790. x0, y0 = old_coords
  3791. x1, y1 = coords
  3792. pt1 = (x0, y0)
  3793. pt2 = (x1, y0)
  3794. pt3 = (x1, y1)
  3795. pt4 = (x0, y1)
  3796. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3797. color_t = Color(face_color)
  3798. color_t.alpha = 0.3
  3799. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3800. layer=0, tolerance=None)
  3801. def on_file_new_click(self):
  3802. if self.collection.get_list():
  3803. msgbox = QtWidgets.QMessageBox()
  3804. # msgbox.setText("<B>Save changes ...</B>")
  3805. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3806. "Creating a New project will delete them.\n"
  3807. "Do you want to Save the project?")
  3808. msgbox.setWindowTitle("Save changes")
  3809. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3810. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3811. QtWidgets.QMessageBox.No)
  3812. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3813. response = msgbox.exec_()
  3814. if response == QtWidgets.QMessageBox.Yes:
  3815. self.on_file_saveprojectas()
  3816. elif response == QtWidgets.QMessageBox.Cancel:
  3817. return
  3818. self.on_file_new()
  3819. else:
  3820. self.on_file_new()
  3821. self.inform.emit("[success] New Project created...")
  3822. def on_file_new(self):
  3823. """
  3824. Callback for menu item File->New. Returns the application to its
  3825. startup state. This method is thread-safe.
  3826. :return: None
  3827. """
  3828. self.report_usage("on_file_new")
  3829. # Remove everything from memory
  3830. App.log.debug("on_file_new()")
  3831. # Clear pool
  3832. self.clear_pool()
  3833. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3834. self.init_tcl()
  3835. self.delete_selection_shape()
  3836. self.collection.delete_all()
  3837. self.setup_component_editor()
  3838. # Clear project filename
  3839. self.project_filename = None
  3840. # Load the application defaults
  3841. self.load_defaults(filename='current_defaults')
  3842. # Re-fresh project options
  3843. self.on_options_app2project()
  3844. # Init Tools
  3845. self.init_tools()
  3846. # take the focus of the Notebook on Project Tab.
  3847. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3848. def obj_properties(self):
  3849. self.report_usage("obj_properties()")
  3850. self.properties_tool.run()
  3851. def obj_move(self):
  3852. self.report_usage("obj_move()")
  3853. self.move_tool.run()
  3854. def on_fileopengerber(self):
  3855. """
  3856. File menu callback for opening a Gerber.
  3857. :return: None
  3858. """
  3859. self.report_usage("on_fileopengerber")
  3860. App.log.debug("on_fileopengerber()")
  3861. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3862. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3863. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3864. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3865. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3866. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3867. "Allegro Files (*.art);;" \
  3868. "Mentor Files (*.pho *.gdo);;" \
  3869. "All Files (*.*)"
  3870. try:
  3871. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  3872. directory=self.get_last_folder(), filter=_filter_)
  3873. except TypeError:
  3874. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  3875. filenames = [str(filename) for filename in filenames]
  3876. if len(filenames) == 0:
  3877. self.inform.emit("[WARNING_NOTCL]Open Gerber cancelled.")
  3878. else:
  3879. for filename in filenames:
  3880. if filename != '':
  3881. self.worker_task.emit({'fcn': self.open_gerber,
  3882. 'params': [filename]})
  3883. def on_fileopengerber_follow(self):
  3884. """
  3885. File menu callback for opening a Gerber.
  3886. :return: None
  3887. """
  3888. self.report_usage("on_fileopengerber_follow")
  3889. App.log.debug("on_fileopengerber_follow()")
  3890. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3891. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3892. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3893. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3894. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3895. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3896. "Allegro Files (*.art);;" \
  3897. "Mentor Files (*.pho *.gdo);;" \
  3898. "All Files (*.*)"
  3899. try:
  3900. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3901. directory=self.get_last_folder(), filter=_filter_)
  3902. except TypeError:
  3903. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3904. # The Qt methods above will return a QString which can cause problems later.
  3905. # So far json.dump() will fail to serialize it.
  3906. # TODO: Improve the serialization methods and remove this fix.
  3907. filename = str(filename)
  3908. follow = True
  3909. if filename == "":
  3910. self.inform.emit("[WARNING_NOTCL]Open Gerber-Follow cancelled.")
  3911. else:
  3912. self.worker_task.emit({'fcn': self.open_gerber,
  3913. 'params': [filename, follow]})
  3914. def on_fileopenexcellon(self):
  3915. """
  3916. File menu callback for opening an Excellon file.
  3917. :return: None
  3918. """
  3919. self.report_usage("on_fileopenexcellon")
  3920. App.log.debug("on_fileopenexcellon()")
  3921. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3922. "All Files (*.*)"
  3923. try:
  3924. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  3925. directory=self.get_last_folder(), filter=_filter_)
  3926. except TypeError:
  3927. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  3928. filenames = [str(filename) for filename in filenames]
  3929. if len(filenames) == 0:
  3930. self.inform.emit("[WARNING_NOTCL]Open Excellon cancelled.")
  3931. else:
  3932. for filename in filenames:
  3933. if filename != '':
  3934. self.worker_task.emit({'fcn': self.open_excellon,
  3935. 'params': [filename]})
  3936. def on_fileopengcode(self):
  3937. """
  3938. File menu call back for opening gcode.
  3939. :return: None
  3940. """
  3941. self.report_usage("on_fileopengcode")
  3942. App.log.debug("on_fileopengcode()")
  3943. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3944. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3945. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3946. "All Files (*.*)"
  3947. try:
  3948. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  3949. directory=self.get_last_folder(), filter=_filter_)
  3950. except TypeError:
  3951. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  3952. filenames = [str(filename) for filename in filenames]
  3953. if len(filenames) == 0:
  3954. self.inform.emit("[WARNING_NOTCL]Open G-Code cancelled.")
  3955. else:
  3956. for filename in filenames:
  3957. if filename != '':
  3958. self.worker_task.emit({'fcn': self.open_gcode,
  3959. 'params': [filename]})
  3960. def on_file_openproject(self):
  3961. """
  3962. File menu callback for opening a project.
  3963. :return: None
  3964. """
  3965. self.report_usage("on_file_openproject")
  3966. App.log.debug("on_file_openproject()")
  3967. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3968. try:
  3969. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3970. directory=self.get_last_folder(), filter=_filter_)
  3971. except TypeError:
  3972. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3973. # The Qt methods above will return a QString which can cause problems later.
  3974. # So far json.dump() will fail to serialize it.
  3975. # TODO: Improve the serialization methods and remove this fix.
  3976. filename = str(filename)
  3977. if filename == "":
  3978. self.inform.emit("[WARNING_NOTCL]Open Project cancelled.")
  3979. else:
  3980. # self.worker_task.emit({'fcn': self.open_project,
  3981. # 'params': [filename]})
  3982. # The above was failing because open_project() is not
  3983. # thread safe. The new_project()
  3984. self.open_project(filename)
  3985. def on_file_exportsvg(self):
  3986. """
  3987. Callback for menu item File->Export SVG.
  3988. :return: None
  3989. """
  3990. self.report_usage("on_file_exportsvg")
  3991. App.log.debug("on_file_exportsvg()")
  3992. obj = self.collection.get_active()
  3993. if obj is None:
  3994. self.inform.emit("WARNING: No object selected.")
  3995. msg = "Please Select a Geometry object to export"
  3996. msgbox = QtWidgets.QMessageBox()
  3997. msgbox.setInformativeText(msg)
  3998. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3999. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4000. msgbox.exec_()
  4001. return
  4002. # Check for more compatible types and add as required
  4003. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4004. and not isinstance(obj, FlatCAMExcellon)):
  4005. msg = "[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used."
  4006. msgbox = QtWidgets.QMessageBox()
  4007. msgbox.setInformativeText(msg)
  4008. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4009. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4010. msgbox.exec_()
  4011. return
  4012. name = self.collection.get_active().options["name"]
  4013. filter = "SVG File (*.svg);;All Files (*.*)"
  4014. try:
  4015. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4016. caption="Export SVG",
  4017. directory=self.get_last_save_folder() + '/' + str(name),
  4018. filter=filter)
  4019. except TypeError:
  4020. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  4021. filename = str(filename)
  4022. if filename == "":
  4023. self.inform.emit("[WARNING_NOTCL]Export SVG cancelled.")
  4024. return
  4025. else:
  4026. self.export_svg(name, filename)
  4027. self.file_saved.emit("SVG", filename)
  4028. def on_file_exportpng(self):
  4029. self.report_usage("on_file_exportpng")
  4030. App.log.debug("on_file_exportpng()")
  4031. image = _screenshot()
  4032. data = np.asarray(image)
  4033. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4034. self.inform.emit('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4')
  4035. return
  4036. filter_ = "PNG File (*.png);;All Files (*.*)"
  4037. try:
  4038. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4039. caption="Export PNG Image",
  4040. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4041. filter=filter_)
  4042. except TypeError:
  4043. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter_)
  4044. filename = str(filename)
  4045. if filename == "":
  4046. self.inform.emit("Export PNG cancelled.")
  4047. return
  4048. else:
  4049. write_png(filename, data)
  4050. self.file_saved.emit("png", filename)
  4051. def on_file_exportexcellon(self, altium_format=None):
  4052. """
  4053. Callback for menu item File->Export SVG.
  4054. :return: None
  4055. """
  4056. self.report_usage("on_file_exportexcellon")
  4057. App.log.debug("on_file_exportexcellon()")
  4058. obj = self.collection.get_active()
  4059. if obj is None:
  4060. self.inform.emit("[WARNING_NOTCL] No object selected.")
  4061. msg = "Please Select an Excellon object to export"
  4062. msgbox = QtWidgets.QMessageBox()
  4063. msgbox.setInformativeText(msg)
  4064. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4065. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4066. msgbox.exec_()
  4067. return
  4068. # Check for more compatible types and add as required
  4069. if not isinstance(obj, FlatCAMExcellon):
  4070. msg = "[WARNING_NOTCL] Only Excellon objects can be used."
  4071. msgbox = QtWidgets.QMessageBox()
  4072. msgbox.setInformativeText(msg)
  4073. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4074. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4075. msgbox.exec_()
  4076. return
  4077. name = self.collection.get_active().options["name"]
  4078. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  4079. try:
  4080. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4081. caption="Export Excellon",
  4082. directory=self.get_last_save_folder() + '/' + name,
  4083. filter=filter)
  4084. except TypeError:
  4085. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  4086. filename = str(filename)
  4087. if filename == "":
  4088. self.inform.emit("[WARNING_NOTCL]Export Excellon cancelled.")
  4089. return
  4090. else:
  4091. if altium_format is None:
  4092. self.export_excellon(name, filename)
  4093. self.file_saved.emit("Excellon", filename)
  4094. else:
  4095. self.export_excellon(name, filename, altium_format=True)
  4096. self.file_saved.emit("Excellon", filename)
  4097. def on_file_exportdxf(self):
  4098. """
  4099. Callback for menu item File->Export DXF.
  4100. :return: None
  4101. """
  4102. self.report_usage("on_file_exportdxf")
  4103. App.log.debug("on_file_exportdxf()")
  4104. obj = self.collection.get_active()
  4105. if obj is None:
  4106. self.inform.emit("W[WARNING_NOTCL] No object selected.")
  4107. msg = "Please Select a Geometry object to export"
  4108. msgbox = QtWidgets.QMessageBox()
  4109. msgbox.setInformativeText(msg)
  4110. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4111. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4112. msgbox.exec_()
  4113. return
  4114. # Check for more compatible types and add as required
  4115. if not isinstance(obj, FlatCAMGeometry):
  4116. msg = "[ERROR_NOTCL] Only Geometry objects can be used."
  4117. msgbox = QtWidgets.QMessageBox()
  4118. msgbox.setInformativeText(msg)
  4119. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4120. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4121. msgbox.exec_()
  4122. return
  4123. name = self.collection.get_active().options["name"]
  4124. filter = "DXF File (*.DXF);;All Files (*.*)"
  4125. try:
  4126. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4127. caption="Export DXF",
  4128. directory=self.get_last_save_folder() + '/' + name,
  4129. filter=filter)
  4130. except TypeError:
  4131. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  4132. filename = str(filename)
  4133. if filename == "":
  4134. self.inform.emit("[WARNING_NOTCL]Export DXF cancelled.")
  4135. return
  4136. else:
  4137. self.export_dxf(name, filename)
  4138. self.file_saved.emit("DXF", filename)
  4139. def on_file_importsvg(self, type_of_obj):
  4140. """
  4141. Callback for menu item File->Import SVG.
  4142. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4143. :type type_of_obj: str
  4144. :return: None
  4145. """
  4146. self.report_usage("on_file_importsvg")
  4147. App.log.debug("on_file_importsvg()")
  4148. filter = "SVG File (*.svg);;All Files (*.*)"
  4149. try:
  4150. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  4151. directory=self.get_last_folder(), filter=filter)
  4152. except TypeError:
  4153. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  4154. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4155. type_of_obj = "geometry"
  4156. filenames = [str(filename) for filename in filenames]
  4157. if len(filenames) == 0:
  4158. self.inform.emit("[WARNING_NOTCL]Open SVG cancelled.")
  4159. else:
  4160. for filename in filenames:
  4161. if filename != '':
  4162. self.worker_task.emit({'fcn': self.import_svg,
  4163. 'params': [filename, type_of_obj]})
  4164. def on_file_importdxf(self, type_of_obj):
  4165. """
  4166. Callback for menu item File->Import DXF.
  4167. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4168. :type type_of_obj: str
  4169. :return: None
  4170. """
  4171. self.report_usage("on_file_importdxf")
  4172. App.log.debug("on_file_importdxf()")
  4173. filter = "DXF File (*.DXF);;All Files (*.*)"
  4174. try:
  4175. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  4176. directory=self.get_last_folder(), filter=filter)
  4177. except TypeError:
  4178. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  4179. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4180. type_of_obj = "geometry"
  4181. filenames = [str(filename) for filename in filenames]
  4182. if len(filenames) == 0:
  4183. self.inform.emit("[WARNING_NOTCL]Open DXF cancelled.")
  4184. else:
  4185. for filename in filenames:
  4186. if filename != '':
  4187. self.worker_task.emit({'fcn': self.import_dxf,
  4188. 'params': [filename, type_of_obj]})
  4189. def on_filerunscript(self):
  4190. """
  4191. File menu callback for loading and running a TCL script.
  4192. :return: None
  4193. """
  4194. self.report_usage("on_filerunscript")
  4195. App.log.debug("on_file_runscript()")
  4196. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4197. try:
  4198. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  4199. directory=self.get_last_folder(), filter=_filter_)
  4200. except TypeError:
  4201. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  4202. # The Qt methods above will return a QString which can cause problems later.
  4203. # So far json.dump() will fail to serialize it.
  4204. # TODO: Improve the serialization methods and remove this fix.
  4205. filename = str(filename)
  4206. if filename == "":
  4207. self.inform.emit("[WARNING_NOTCL]Open TCL script cancelled.")
  4208. else:
  4209. try:
  4210. with open(filename, "r") as tcl_script:
  4211. cmd_line_shellfile_content = tcl_script.read()
  4212. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4213. except Exception as ext:
  4214. print("ERROR: ", ext)
  4215. sys.exit(2)
  4216. def on_file_saveproject(self):
  4217. """
  4218. Callback for menu item File->Save Project. Saves the project to
  4219. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4220. if set to None. The project is saved by calling ``self.save_project()``.
  4221. :return: None
  4222. """
  4223. self.report_usage("on_file_saveproject")
  4224. if self.project_filename is None:
  4225. self.on_file_saveprojectas()
  4226. else:
  4227. self.worker_task.emit({'fcn': self.save_project,
  4228. 'params': [self.project_filename]})
  4229. # self.save_project(self.project_filename)
  4230. self.file_opened.emit("project", self.project_filename)
  4231. self.file_saved.emit("project", self.project_filename)
  4232. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4233. """
  4234. Callback for menu item File->Save Project As... Opens a file
  4235. chooser and saves the project to the given file via
  4236. ``self.save_project()``.
  4237. :return: None
  4238. """
  4239. self.report_usage("on_file_saveprojectas")
  4240. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4241. try:
  4242. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4243. caption="Save Project As ...",
  4244. directory=self.get_last_save_folder() + '/Project_' + self.date.replace('-', ''),
  4245. filter=filter_)
  4246. except TypeError:
  4247. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter_)
  4248. filename = str(filename)
  4249. if filename == '':
  4250. self.inform.emit("[WARNING_NOTCL]Save Project cancelled.")
  4251. return
  4252. try:
  4253. f = open(filename, 'r')
  4254. f.close()
  4255. exists = True
  4256. except IOError:
  4257. exists = False
  4258. msg = "File exists. Overwrite?"
  4259. if exists:
  4260. msgbox = QtWidgets.QMessageBox()
  4261. msgbox.setInformativeText(msg)
  4262. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4263. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4264. result = msgbox.exec_()
  4265. if result ==QtWidgets.QMessageBox.Cancel:
  4266. return
  4267. if thread is True:
  4268. self.worker_task.emit({'fcn': self.save_project,
  4269. 'params': [filename]})
  4270. else:
  4271. self.save_project(filename)
  4272. # self.save_project(filename)
  4273. self.file_opened.emit("project", filename)
  4274. self.file_saved.emit("project", filename)
  4275. if not make_copy:
  4276. self.project_filename = filename
  4277. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4278. """
  4279. Exports a Geometry Object to an SVG file.
  4280. :param filename: Path to the SVG file to save to.
  4281. :return:
  4282. """
  4283. self.report_usage("export_svg()")
  4284. if filename is None:
  4285. filename = self.defaults["global_last_save_folder"]
  4286. self.log.debug("export_svg()")
  4287. try:
  4288. obj = self.collection.get_by_name(str(obj_name))
  4289. except:
  4290. # TODO: The return behavior has not been established... should raise exception?
  4291. return "Could not retrieve object: %s" % obj_name
  4292. with self.proc_container.new("Exporting SVG") as proc:
  4293. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4294. # Determine bounding area for svg export
  4295. bounds = obj.bounds()
  4296. size = obj.size()
  4297. # Convert everything to strings for use in the xml doc
  4298. svgwidth = str(size[0])
  4299. svgheight = str(size[1])
  4300. minx = str(bounds[0])
  4301. miny = str(bounds[1] - size[1])
  4302. uom = obj.units.lower()
  4303. # Add a SVG Header and footer to the svg output from shapely
  4304. # The transform flips the Y Axis so that everything renders
  4305. # properly within svg apps such as inkscape
  4306. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4307. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4308. svg_header += 'width="' + svgwidth + uom + '" '
  4309. svg_header += 'height="' + svgheight + uom + '" '
  4310. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4311. svg_header += '<g transform="scale(1,-1)">'
  4312. svg_footer = '</g> </svg>'
  4313. svg_elem = svg_header + exported_svg + svg_footer
  4314. # Parse the xml through a xml parser just to add line feeds
  4315. # and to make it look more pretty for the output
  4316. svgcode = parse_xml_string(svg_elem)
  4317. with open(filename, 'w') as fp:
  4318. fp.write(svgcode.toprettyxml())
  4319. self.file_saved.emit("SVG", filename)
  4320. self.inform.emit("[success] SVG file exported to " + filename)
  4321. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4322. """
  4323. Exports a Geometry Object to an SVG file in negative.
  4324. :param filename: Path to the SVG file to save to.
  4325. :param: use_thread: If True use threads
  4326. :type: Bool
  4327. :return:
  4328. """
  4329. self.report_usage("export_negative()")
  4330. if filename is None:
  4331. filename = self.defaults["global_last_save_folder"]
  4332. self.log.debug("export_svg() negative")
  4333. try:
  4334. obj = self.collection.get_by_name(str(obj_name))
  4335. except:
  4336. # TODO: The return behavior has not been established... should raise exception?
  4337. return "Could not retrieve object: %s" % obj_name
  4338. try:
  4339. box = self.collection.get_by_name(str(box_name))
  4340. except:
  4341. # TODO: The return behavior has not been established... should raise exception?
  4342. return "Could not retrieve object: %s" % box_name
  4343. if box is None:
  4344. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4345. box = obj
  4346. def make_negative_film():
  4347. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4348. self.progress.emit(40)
  4349. # Determine bounding area for svg export
  4350. bounds = box.bounds()
  4351. size = box.size()
  4352. uom = obj.units.lower()
  4353. # Convert everything to strings for use in the xml doc
  4354. svgwidth = str(size[0] + (2 * boundary))
  4355. svgheight = str(size[1] + (2 * boundary))
  4356. minx = str(bounds[0] - boundary)
  4357. miny = str(bounds[1] + boundary + size[1])
  4358. miny_rect = str(bounds[1] - boundary)
  4359. # Add a SVG Header and footer to the svg output from shapely
  4360. # The transform flips the Y Axis so that everything renders
  4361. # properly within svg apps such as inkscape
  4362. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4363. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4364. svg_header += 'width="' + svgwidth + uom + '" '
  4365. svg_header += 'height="' + svgheight + uom + '" '
  4366. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4367. svg_header += '>'
  4368. svg_header += '<g transform="scale(1,-1)">'
  4369. svg_footer = '</g> </svg>'
  4370. self.progress.emit(60)
  4371. # Change the attributes of the exported SVG
  4372. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4373. # We set opacity to maximum
  4374. # We set the color to WHITE
  4375. root = ET.fromstring(exported_svg)
  4376. for child in root:
  4377. child.set('fill', '#FFFFFF')
  4378. child.set('opacity', '1.0')
  4379. child.set('stroke', '#FFFFFF')
  4380. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4381. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4382. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4383. first_svg_elem_tag = 'rect'
  4384. first_svg_elem_attribs = {
  4385. 'x': minx,
  4386. 'y': miny_rect,
  4387. 'width': svgwidth,
  4388. 'height': svgheight,
  4389. 'id': 'neg_rect',
  4390. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4391. }
  4392. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4393. exported_svg = ET.tostring(root)
  4394. svg_elem = svg_header + str(exported_svg) + svg_footer
  4395. self.progress.emit(80)
  4396. # Parse the xml through a xml parser just to add line feeds
  4397. # and to make it look more pretty for the output
  4398. doc = parse_xml_string(svg_elem)
  4399. with open(filename, 'w') as fp:
  4400. fp.write(doc.toprettyxml())
  4401. self.progress.emit(100)
  4402. self.file_saved.emit("SVG", filename)
  4403. self.inform.emit("[success] SVG file exported to " + filename)
  4404. if use_thread is True:
  4405. proc = self.proc_container.new("Generating Film ... Please wait.")
  4406. def job_thread_film(app_obj):
  4407. try:
  4408. make_negative_film()
  4409. except Exception as e:
  4410. proc.done()
  4411. return
  4412. proc.done()
  4413. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4414. else:
  4415. make_negative_film()
  4416. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4417. """
  4418. Exports a Geometry Object to an SVG file in negative.
  4419. :param filename: Path to the SVG file to save to.
  4420. :param: use_thread: If True use threads
  4421. :type: Bool
  4422. :return:
  4423. """
  4424. self.report_usage("export_svg_black()")
  4425. if filename is None:
  4426. filename = self.defaults["global_last_save_folder"]
  4427. self.log.debug("export_svg() black")
  4428. try:
  4429. obj = self.collection.get_by_name(str(obj_name))
  4430. except:
  4431. # TODO: The return behavior has not been established... should raise exception?
  4432. return "Could not retrieve object: %s" % obj_name
  4433. try:
  4434. box = self.collection.get_by_name(str(box_name))
  4435. except:
  4436. # TODO: The return behavior has not been established... should raise exception?
  4437. return "Could not retrieve object: %s" % box_name
  4438. if box is None:
  4439. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4440. box = obj
  4441. def make_black_film():
  4442. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4443. self.progress.emit(40)
  4444. # Change the attributes of the exported SVG
  4445. # We don't need stroke-width
  4446. # We set opacity to maximum
  4447. # We set the colour to WHITE
  4448. root = ET.fromstring(exported_svg)
  4449. for child in root:
  4450. child.set('fill', '#000000')
  4451. child.set('opacity', '1.0')
  4452. child.set('stroke', '#000000')
  4453. exported_svg = ET.tostring(root)
  4454. # Determine bounding area for svg export
  4455. bounds = box.bounds()
  4456. size = box.size()
  4457. # This contain the measure units
  4458. uom = obj.units.lower()
  4459. # Define a boundary around SVG of about 1.0mm (~39mils)
  4460. if uom in "mm":
  4461. boundary = 1.0
  4462. else:
  4463. boundary = 0.0393701
  4464. self.progress.emit(80)
  4465. # Convert everything to strings for use in the xml doc
  4466. svgwidth = str(size[0] + (2 * boundary))
  4467. svgheight = str(size[1] + (2 * boundary))
  4468. minx = str(bounds[0] - boundary)
  4469. miny = str(bounds[1] + boundary + size[1])
  4470. self.log.debug(minx)
  4471. self.log.debug(miny)
  4472. # Add a SVG Header and footer to the svg output from shapely
  4473. # The transform flips the Y Axis so that everything renders
  4474. # properly within svg apps such as inkscape
  4475. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4476. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4477. svg_header += 'width="' + svgwidth + uom + '" '
  4478. svg_header += 'height="' + svgheight + uom + '" '
  4479. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4480. svg_header += '>'
  4481. svg_header += '<g transform="scale(1,-1)">'
  4482. svg_footer = '</g> </svg>'
  4483. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4484. self.progress.emit(90)
  4485. # Parse the xml through a xml parser just to add line feeds
  4486. # and to make it look more pretty for the output
  4487. doc = parse_xml_string(svg_elem)
  4488. with open(filename, 'w') as fp:
  4489. fp.write(doc.toprettyxml())
  4490. self.progress.emit(100)
  4491. self.file_saved.emit("SVG", filename)
  4492. self.inform.emit("[success] SVG file exported to " + filename)
  4493. if use_thread is True:
  4494. proc = self.proc_container.new("Generating Film ... Please wait.")
  4495. def job_thread_film(app_obj):
  4496. try:
  4497. make_black_film()
  4498. except Exception as e:
  4499. proc.done()
  4500. return
  4501. proc.done()
  4502. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4503. else:
  4504. make_black_film()
  4505. def export_excellon(self, obj_name, filename, use_thread=True):
  4506. """
  4507. Exports a Geometry Object to an Excellon file.
  4508. :param filename: Path to the Excellon file to save to.
  4509. :return:
  4510. """
  4511. self.report_usage("export_excellon()")
  4512. if filename is None:
  4513. filename = self.defaults["global_last_save_folder"]
  4514. self.log.debug("export_excellon()")
  4515. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  4516. self.defaults["excellon_exp_decimals"]
  4517. )
  4518. units = ''
  4519. try:
  4520. obj = self.collection.get_by_name(str(obj_name))
  4521. except:
  4522. # TODO: The return behavior has not been established... should raise exception?
  4523. return "Could not retrieve object: %s" % obj_name
  4524. # updated units
  4525. units = self.defaults["excellon_exp_units"]
  4526. whole = self.defaults["excellon_exp_integer"]
  4527. fract = self.defaults["excellon_exp_decimals"]
  4528. def make_excellon():
  4529. try:
  4530. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4531. header = 'M48\n'
  4532. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4533. (str(self.app.version), str(self.app.version_date))
  4534. header += ';Filename: %s' % str(obj_name) + '\n'
  4535. header += ';Created on : %s' % time_str + '\n'
  4536. if self.defaults["excellon_exp_format"] == 'dec':
  4537. has_slots, excellon_code = obj.export_excellon_decimals(whole, fract, units)
  4538. header += units + '\n'
  4539. for tool in obj.tools:
  4540. if units == 'METRIC':
  4541. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  4542. else:
  4543. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4544. else:
  4545. has_slots, excellon_code = obj.export_excellon_ndecimals(whole, fract, units)
  4546. header += '%s,%s\n' % (units, self.defaults["excellon_exp_zeros"])
  4547. header += format_exc
  4548. for tool in obj.tools:
  4549. if units == 'METRIC':
  4550. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  4551. '%.2f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  4552. else:
  4553. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4554. header += '%\n'
  4555. footer = 'M30\n'
  4556. exported_excellon = header
  4557. exported_excellon += excellon_code
  4558. exported_excellon += footer
  4559. with open(filename, 'w') as fp:
  4560. fp.write(exported_excellon)
  4561. self.file_saved.emit("Excellon", filename)
  4562. self.inform.emit("[success] Excellon file exported to " + filename)
  4563. except:
  4564. return 'fail'
  4565. if use_thread is True:
  4566. with self.proc_container.new("Exporting Excellon") as proc:
  4567. def job_thread_exc(app_obj):
  4568. ret = make_excellon()
  4569. if ret == 'fail':
  4570. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4571. return
  4572. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4573. else:
  4574. ret = make_excellon()
  4575. if ret == 'fail':
  4576. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4577. return
  4578. def export_dxf(self, obj_name, filename, use_thread=True):
  4579. """
  4580. Exports a Geometry Object to an DXF file.
  4581. :param filename: Path to the DXF file to save to.
  4582. :return:
  4583. """
  4584. self.report_usage("export_dxf()")
  4585. if filename is None:
  4586. filename = self.defaults["global_last_save_folder"]
  4587. self.log.debug("export_dxf()")
  4588. format_exc = ''
  4589. units = ''
  4590. try:
  4591. obj = self.collection.get_by_name(str(obj_name))
  4592. except:
  4593. # TODO: The return behavior has not been established... should raise exception?
  4594. return "Could not retrieve object: %s" % obj_name
  4595. # updated units
  4596. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4597. if units == 'IN' or units == 'INCH':
  4598. units = 'INCH'
  4599. elif units == 'MM' or units == 'METIRC':
  4600. units ='METRIC'
  4601. def make_dxf():
  4602. try:
  4603. dxf_code = obj.export_dxf()
  4604. dxf_code.saveas(filename)
  4605. self.file_saved.emit("DXF", filename)
  4606. self.inform.emit("[success] DXF file exported to " + filename)
  4607. except:
  4608. return 'fail'
  4609. if use_thread is True:
  4610. with self.proc_container.new("Exporting DXF") as proc:
  4611. def job_thread_exc(app_obj):
  4612. ret = make_dxf()
  4613. if ret == 'fail':
  4614. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4615. return
  4616. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4617. else:
  4618. ret = make_dxf()
  4619. if ret == 'fail':
  4620. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4621. return
  4622. def import_svg(self, filename, geo_type='geometry', outname=None):
  4623. """
  4624. Adds a new Geometry Object to the projects and populates
  4625. it with shapes extracted from the SVG file.
  4626. :param filename: Path to the SVG file.
  4627. :param outname:
  4628. :return:
  4629. """
  4630. self.report_usage("import_svg()")
  4631. obj_type = ""
  4632. if geo_type is None or geo_type == "geometry":
  4633. obj_type = "geometry"
  4634. elif geo_type == "gerber":
  4635. obj_type = geo_type
  4636. else:
  4637. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4638. "Only Geometry and Gerber are supported")
  4639. return
  4640. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4641. def obj_init(geo_obj, app_obj):
  4642. geo_obj.import_svg(filename, obj_type, units=units)
  4643. geo_obj.multigeo = False
  4644. with self.proc_container.new("Importing SVG") as proc:
  4645. # Object name
  4646. name = outname or filename.split('/')[-1].split('\\')[-1]
  4647. self.new_object(obj_type, name, obj_init, autoselected=False)
  4648. self.progress.emit(20)
  4649. # Register recent file
  4650. self.file_opened.emit("svg", filename)
  4651. # GUI feedback
  4652. self.inform.emit("[success] Opened: " + filename)
  4653. self.progress.emit(100)
  4654. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4655. """
  4656. Adds a new Geometry Object to the projects and populates
  4657. it with shapes extracted from the DXF file.
  4658. :param filename: Path to the DXF file.
  4659. :param outname:
  4660. :type putname: str
  4661. :return:
  4662. """
  4663. self.report_usage("import_dxf()")
  4664. obj_type = ""
  4665. if geo_type is None or geo_type == "geometry":
  4666. obj_type = "geometry"
  4667. elif geo_type == "gerber":
  4668. obj_type = geo_type
  4669. else:
  4670. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4671. "Only Geometry and Gerber are supported")
  4672. return
  4673. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4674. def obj_init(geo_obj, app_obj):
  4675. geo_obj.import_dxf(filename, obj_type, units=units)
  4676. geo_obj.multigeo = False
  4677. with self.proc_container.new("Importing DXF") as proc:
  4678. # Object name
  4679. name = outname or filename.split('/')[-1].split('\\')[-1]
  4680. self.new_object(obj_type, name, obj_init, autoselected=False)
  4681. self.progress.emit(20)
  4682. # Register recent file
  4683. self.file_opened.emit("dxf", filename)
  4684. # GUI feedback
  4685. self.inform.emit("[success] Opened: " + filename)
  4686. self.progress.emit(100)
  4687. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4688. """
  4689. Adds a new Geometry Object to the projects and populates
  4690. it with shapes extracted from the SVG file.
  4691. :param filename: Path to the SVG file.
  4692. :param outname:
  4693. :return:
  4694. """
  4695. self.report_usage("import_image()")
  4696. obj_type = ""
  4697. if type is None or type == "geometry":
  4698. obj_type = "geometry"
  4699. elif type == "gerber":
  4700. obj_type = type
  4701. else:
  4702. self.inform.emit("[ERROR_NOTCL] Not supported type was picked as parameter. "
  4703. "Only Geometry and Gerber are supported")
  4704. return
  4705. def obj_init(geo_obj, app_obj):
  4706. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4707. geo_obj.multigeo = False
  4708. with self.proc_container.new("Importing Image") as proc:
  4709. # Object name
  4710. name = outname or filename.split('/')[-1].split('\\')[-1]
  4711. units = self.general_options_form.general_app_group.units_radio.get_value()
  4712. self.new_object(obj_type, name, obj_init)
  4713. self.progress.emit(20)
  4714. # Register recent file
  4715. self.file_opened.emit("image", filename)
  4716. # GUI feedback
  4717. self.inform.emit("[success] Opened: " + filename)
  4718. self.progress.emit(100)
  4719. def open_gerber(self, filename, follow=False, outname=None):
  4720. """
  4721. Opens a Gerber file, parses it and creates a new object for
  4722. it in the program. Thread-safe.
  4723. :param outname: Name of the resulting object. None causes the
  4724. name to be that of the file.
  4725. :param filename: Gerber file filename
  4726. :type filename: str
  4727. :param follow: If true, the parser will not create polygons, just lines
  4728. following the gerber path.
  4729. :type follow: bool
  4730. :return: None
  4731. """
  4732. # How the object should be initialized
  4733. def obj_init(gerber_obj, app_obj):
  4734. assert isinstance(gerber_obj, FlatCAMGerber), \
  4735. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4736. # Opening the file happens here
  4737. self.progress.emit(30)
  4738. try:
  4739. gerber_obj.parse_file(filename, follow=follow)
  4740. except IOError:
  4741. app_obj.inform.emit("[ERROR_NOTCL] Failed to open file: " + filename)
  4742. app_obj.progress.emit(0)
  4743. self.inform.emit('[ERROR_NOTCL] Failed to open file: ' + filename)
  4744. return "fail"
  4745. except ParseError as err:
  4746. app_obj.inform.emit("[ERROR_NOTCL] Failed to parse file: " + filename + ". " + str(err))
  4747. app_obj.progress.emit(0)
  4748. self.log.error(str(err))
  4749. return "fail"
  4750. except:
  4751. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  4752. msg += traceback.format_exc()
  4753. app_obj.inform.emit(msg)
  4754. return "fail"
  4755. if gerber_obj.is_empty():
  4756. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  4757. # self.collection.set_active(gerber_obj.options["name"])
  4758. # self.collection.delete_active()
  4759. self.inform.emit("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation.")
  4760. return "fail"
  4761. # Further parsing
  4762. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4763. if follow is False:
  4764. App.log.debug("open_gerber()")
  4765. else:
  4766. App.log.debug("open_gerber() with 'follow' attribute")
  4767. with self.proc_container.new("Opening Gerber") as proc:
  4768. self.progress.emit(10)
  4769. # Object name
  4770. name = outname or filename.split('/')[-1].split('\\')[-1]
  4771. ### Object creation ###
  4772. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4773. if ret == 'fail':
  4774. self.inform.emit('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.')
  4775. return
  4776. # Register recent file
  4777. self.file_opened.emit("gerber", filename)
  4778. self.progress.emit(100)
  4779. # GUI feedback
  4780. self.inform.emit("[success] Opened: " + filename)
  4781. def open_excellon(self, filename, outname=None):
  4782. """
  4783. Opens an Excellon file, parses it and creates a new object for
  4784. it in the program. Thread-safe.
  4785. :param outname: Name of the resulting object. None causes the
  4786. name to be that of the file.
  4787. :param filename: Excellon file filename
  4788. :type filename: str
  4789. :return: None
  4790. """
  4791. App.log.debug("open_excellon()")
  4792. #self.progress.emit(10)
  4793. # How the object should be initialized
  4794. def obj_init(excellon_obj, app_obj):
  4795. # self.progress.emit(20)
  4796. try:
  4797. ret = excellon_obj.parse_file(filename)
  4798. if ret == "fail":
  4799. log.debug("Excellon parsing failed.")
  4800. self.inform.emit("[ERROR_NOTCL] This is not Excellon file.")
  4801. return "fail"
  4802. except IOError:
  4803. app_obj.inform.emit("[ERROR_NOTCL] Cannot open file: " + filename)
  4804. log.debug("Could not open Excellon object.")
  4805. self.progress.emit(0) # TODO: self and app_bjj mixed
  4806. return "fail"
  4807. except:
  4808. msg = "[ERROR_NOTCL] An internal error has occurred. See shell.\n"
  4809. msg += traceback.format_exc()
  4810. app_obj.inform.emit(msg)
  4811. return "fail"
  4812. ret = excellon_obj.create_geometry()
  4813. if ret == 'fail':
  4814. log.debug("Could not create geometry for Excellon object.")
  4815. return "fail"
  4816. # if excellon_obj.is_empty():
  4817. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  4818. # return "fail"
  4819. for tool in excellon_obj.tools:
  4820. if excellon_obj.tools[tool]['solid_geometry']:
  4821. return
  4822. app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  4823. return "fail"
  4824. with self.proc_container.new("Opening Excellon."):
  4825. # Object name
  4826. name = outname or filename.split('/')[-1].split('\\')[-1]
  4827. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4828. if ret == 'fail':
  4829. self.inform.emit('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.')
  4830. return
  4831. # Register recent file
  4832. self.file_opened.emit("excellon", filename)
  4833. # GUI feedback
  4834. self.inform.emit("[success] Opened: " + filename)
  4835. # self.progress.emit(100)
  4836. def open_gcode(self, filename, outname=None):
  4837. """
  4838. Opens a G-gcode file, parses it and creates a new object for
  4839. it in the program. Thread-safe.
  4840. :param outname: Name of the resulting object. None causes the
  4841. name to be that of the file.
  4842. :param filename: G-code file filename
  4843. :type filename: str
  4844. :return: None
  4845. """
  4846. App.log.debug("open_gcode()")
  4847. # How the object should be initialized
  4848. def obj_init(job_obj, app_obj_):
  4849. """
  4850. :type app_obj_: App
  4851. """
  4852. assert isinstance(app_obj_, App), \
  4853. "Initializer expected App, got %s" % type(app_obj_)
  4854. self.progress.emit(10)
  4855. try:
  4856. f = open(filename)
  4857. gcode = f.read()
  4858. f.close()
  4859. except IOError:
  4860. app_obj_.inform.emit("[ERROR_NOTCL] Failed to open " + filename)
  4861. self.progress.emit(0)
  4862. return "fail"
  4863. job_obj.gcode = gcode
  4864. self.progress.emit(20)
  4865. ret = job_obj.gcode_parse()
  4866. if ret == "fail":
  4867. self.inform.emit("[ERROR_NOTCL] This is not GCODE")
  4868. return "fail"
  4869. self.progress.emit(60)
  4870. job_obj.create_geometry()
  4871. with self.proc_container.new("Opening G-Code."):
  4872. # Object name
  4873. name = outname or filename.split('/')[-1].split('\\')[-1]
  4874. # New object creation and file processing
  4875. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4876. if ret == 'fail':
  4877. self.inform.emit("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4878. "Attempting to create a FlatCAM CNCJob Object from "
  4879. "G-Code file failed during processing")
  4880. return "fail"
  4881. # Register recent file
  4882. self.file_opened.emit("cncjob", filename)
  4883. # GUI feedback
  4884. self.inform.emit("[success] Opened: " + filename)
  4885. self.progress.emit(100)
  4886. def open_project(self, filename, run_from_arg=None):
  4887. """
  4888. Loads a project from the specified file.
  4889. 1) Loads and parses file
  4890. 2) Registers the file as recently opened.
  4891. 3) Calls on_file_new()
  4892. 4) Updates options
  4893. 5) Calls new_object() with the object's from_dict() as init method.
  4894. 6) Calls plot_all()
  4895. :param filename: Name of the file from which to load.
  4896. :type filename: str
  4897. :return: None
  4898. """
  4899. App.log.debug("Opening project: " + filename)
  4900. # Open and parse
  4901. try:
  4902. f = open(filename, 'r')
  4903. except IOError:
  4904. App.log.error("Failed to open project file: %s" % filename)
  4905. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  4906. return
  4907. try:
  4908. d = json.load(f, object_hook=dict2obj)
  4909. except:
  4910. App.log.error("Failed to parse project file: %s" % filename)
  4911. self.inform.emit("[ERROR_NOTCL] Failed to parse project file: %s" % filename)
  4912. f.close()
  4913. return
  4914. self.file_opened.emit("project", filename)
  4915. # Clear the current project
  4916. ## NOT THREAD SAFE ##
  4917. if run_from_arg is True:
  4918. pass
  4919. else:
  4920. self.on_file_new()
  4921. #Project options
  4922. self.options.update(d['options'])
  4923. self.project_filename = filename
  4924. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4925. self.set_screen_units(self.options["units"])
  4926. # Re create objects
  4927. App.log.debug("Re-creating objects...")
  4928. for obj in d['objs']:
  4929. def obj_init(obj_inst, app_inst):
  4930. obj_inst.from_dict(obj)
  4931. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4932. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4933. # self.plot_all()
  4934. self.inform.emit("[success] Project loaded from: " + filename)
  4935. App.log.debug("Project loaded")
  4936. def propagate_defaults(self, silent=False):
  4937. """
  4938. This method is used to set default values in classes. It's
  4939. an alternative to project options but allows the use
  4940. of values invisible to the user.
  4941. :return: None
  4942. """
  4943. if silent is False:
  4944. self.log.debug("propagate_defaults()")
  4945. # Which objects to update the given parameters.
  4946. routes = {
  4947. "global_zdownrate": CNCjob,
  4948. "excellon_zeros": Excellon,
  4949. "excellon_format_upper_in": Excellon,
  4950. "excellon_format_lower_in": Excellon,
  4951. "excellon_format_upper_mm": Excellon,
  4952. "excellon_format_lower_mm": Excellon,
  4953. "excellon_units": Excellon,
  4954. "gerber_use_buffer_for_union": Gerber,
  4955. "geometry_multidepth": Geometry
  4956. }
  4957. for param in routes:
  4958. if param in routes[param].defaults:
  4959. try:
  4960. routes[param].defaults[param] = self.defaults[param]
  4961. if silent is False:
  4962. self.log.debug(" " + param + " OK")
  4963. except KeyError:
  4964. if silent is False:
  4965. self.log.debug(" ERROR: " + param + " not in defaults.")
  4966. else:
  4967. # Try extracting the name:
  4968. # classname_param here is param in the object
  4969. if param.find(routes[param].__name__.lower() + "_") == 0:
  4970. p = param[len(routes[param].__name__) + 1:]
  4971. if p in routes[param].defaults:
  4972. routes[param].defaults[p] = self.defaults[param]
  4973. if silent is False:
  4974. self.log.debug(" " + param + " OK!")
  4975. def restore_main_win_geom(self):
  4976. try:
  4977. self.ui.setGeometry(self.defaults["global_def_win_x"],
  4978. self.defaults["global_def_win_y"],
  4979. self.defaults["global_def_win_w"],
  4980. self.defaults["global_def_win_h"])
  4981. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  4982. except KeyError:
  4983. pass
  4984. def plot_all(self, zoom=True):
  4985. """
  4986. Re-generates all plots from all objects.
  4987. :return: None
  4988. """
  4989. self.log.debug("Plot_all()")
  4990. for obj in self.collection.get_list():
  4991. def worker_task(obj):
  4992. with self.proc_container.new("Plotting"):
  4993. obj.plot()
  4994. if zoom:
  4995. self.object_plotted.emit(obj)
  4996. # Send to worker
  4997. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  4998. # self.progress.emit(10)
  4999. #
  5000. # def worker_task(app_obj):
  5001. # print "worker task"
  5002. # percentage = 0.1
  5003. # try:
  5004. # delta = 0.9 / len(self.collection.get_list())
  5005. # except ZeroDivisionError:
  5006. # self.progress.emit(0)
  5007. # return
  5008. # for obj in self.collection.get_list():
  5009. # with self.proc_container.new("Plotting"):
  5010. # obj.plot()
  5011. # app_obj.object_plotted.emit(obj)
  5012. #
  5013. # percentage += delta
  5014. # self.progress.emit(int(percentage*100))
  5015. #
  5016. # self.progress.emit(0)
  5017. # self.plots_updated.emit()
  5018. #
  5019. # # Send to worker
  5020. # #self.worker.add_task(worker_task, [self])
  5021. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5022. def register_folder(self, filename):
  5023. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5024. def register_save_folder(self, filename):
  5025. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5026. def set_progress_bar(self, percentage, text=""):
  5027. self.ui.progress_bar.setValue(int(percentage))
  5028. def setup_shell(self):
  5029. """
  5030. Creates shell functions. Runs once at startup.
  5031. :return: None
  5032. """
  5033. self.log.debug("setup_shell()")
  5034. def shelp(p=None):
  5035. if not p:
  5036. return "Available commands:\n" + \
  5037. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5038. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  5039. if p not in commands:
  5040. return "Unknown command: %s" % p
  5041. return commands[p]["help"]
  5042. # --- Migrated to new architecture ---
  5043. # def options(name):
  5044. # ops = self.collection.get_by_name(str(name)).options
  5045. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5046. def h(*args):
  5047. """
  5048. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5049. and standalone parameters into list.
  5050. """
  5051. kwa = {}
  5052. a = []
  5053. n = len(args)
  5054. name = None
  5055. for i in range(n):
  5056. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5057. if match:
  5058. assert name is None
  5059. name = match.group(1)
  5060. continue
  5061. if name is None:
  5062. a.append(args[i])
  5063. else:
  5064. kwa[name] = args[i]
  5065. name = None
  5066. return a, kwa
  5067. @contextmanager
  5068. def wait_signal(signal, timeout=10000):
  5069. """
  5070. Block loop until signal emitted, timeout (ms) elapses
  5071. or unhandled exception happens in a thread.
  5072. :param signal: Signal to wait for.
  5073. """
  5074. loop = QtCore.QEventLoop()
  5075. # Normal termination
  5076. signal.connect(loop.quit)
  5077. # Termination by exception in thread
  5078. self.thread_exception.connect(loop.quit)
  5079. status = {'timed_out': False}
  5080. def report_quit():
  5081. status['timed_out'] = True
  5082. loop.quit()
  5083. yield
  5084. # Temporarily change how exceptions are managed.
  5085. oeh = sys.excepthook
  5086. ex = []
  5087. def except_hook(type_, value, traceback_):
  5088. ex.append(value)
  5089. oeh(type_, value, traceback_)
  5090. sys.excepthook = except_hook
  5091. # Terminate on timeout
  5092. if timeout is not None:
  5093. QtCore.QTimer.singleShot(timeout, report_quit)
  5094. #### Block ####
  5095. loop.exec_()
  5096. # Restore exception management
  5097. sys.excepthook = oeh
  5098. if ex:
  5099. self.raiseTclError(str(ex[0]))
  5100. if status['timed_out']:
  5101. raise Exception('Timed out!')
  5102. def make_docs():
  5103. output = ''
  5104. import collections
  5105. od = collections.OrderedDict(sorted(commands.items()))
  5106. for cmd_, val in od.items():
  5107. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5108. t = val['help']
  5109. usage_i = t.find('>')
  5110. if usage_i < 0:
  5111. expl = t
  5112. output += expl + '\n\n'
  5113. continue
  5114. expl = t[:usage_i - 1]
  5115. output += expl + '\n\n'
  5116. end_usage_i = t[usage_i:].find('\n')
  5117. if end_usage_i < 0:
  5118. end_usage_i = len(t[usage_i:])
  5119. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5120. else:
  5121. extras = t[usage_i+end_usage_i+1:]
  5122. parts = [s.strip() for s in extras.split('\n')]
  5123. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5124. for p in parts:
  5125. output += ' ' + p + '\n\n'
  5126. return output
  5127. '''
  5128. Howto implement TCL shell commands:
  5129. All parameters passed to command should be possible to set as None and test it afterwards.
  5130. This is because we need to see error caused in tcl,
  5131. if None value as default parameter is not allowed TCL will return empty error.
  5132. Use:
  5133. def mycommand(name=None,...):
  5134. Test it like this:
  5135. if name is None:
  5136. self.raise_tcl_error('Argument name is missing.')
  5137. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5138. otherwise we will miss it and processing will silently continue.
  5139. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5140. which is catched in exec_command and displayed in TCL shell console with red background.
  5141. Error in console is displayed with TCL trace.
  5142. This behavior works only within main thread,
  5143. errors with promissed tasks can be catched and detected only with log.
  5144. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5145. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5146. '''
  5147. commands = {
  5148. 'help': {
  5149. 'fcn': shelp,
  5150. 'help': "Shows list of commands."
  5151. },
  5152. }
  5153. # Import/overwrite tcl commands as objects of TclCommand descendants
  5154. # This modifies the variable 'commands'.
  5155. tclCommands.register_all_commands(self, commands)
  5156. # Add commands to the tcl interpreter
  5157. for cmd in commands:
  5158. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5159. # Make the tcl puts function return instead of print to stdout
  5160. self.tcl.eval('''
  5161. rename puts original_puts
  5162. proc puts {args} {
  5163. if {[llength $args] == 1} {
  5164. return "[lindex $args 0]"
  5165. } else {
  5166. eval original_puts $args
  5167. }
  5168. }
  5169. ''')
  5170. def setup_recent_items(self):
  5171. # TODO: Move this to constructor
  5172. icons = {
  5173. "gerber": "share/flatcam_icon16.png",
  5174. "excellon": "share/drill16.png",
  5175. "cncjob": "share/cnc16.png",
  5176. "project": "share/project16.png",
  5177. "svg": "share/geometry16.png",
  5178. "dxf": "share/dxf16.png",
  5179. "image": "share/image16.png"
  5180. }
  5181. openers = {
  5182. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5183. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5184. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5185. 'project': self.open_project,
  5186. 'svg': self.import_svg,
  5187. 'dxf': self.import_dxf,
  5188. 'image': self.import_image
  5189. }
  5190. # Open file
  5191. try:
  5192. f = open(self.data_path + '/recent.json')
  5193. except IOError:
  5194. App.log.error("Failed to load recent item list.")
  5195. self.inform.emit("[ERROR_NOTCL] Failed to load recent item list.")
  5196. return
  5197. try:
  5198. self.recent = json.load(f)
  5199. except json.scanner.JSONDecodeError:
  5200. App.log.error("Failed to parse recent item list.")
  5201. self.inform.emit("[ERROR_NOTCL] Failed to parse recent item list.")
  5202. f.close()
  5203. return
  5204. f.close()
  5205. # Closure needed to create callbacks in a loop.
  5206. # Otherwise late binding occurs.
  5207. def make_callback(func, fname):
  5208. def opener():
  5209. func(fname)
  5210. return opener
  5211. def reset_recent():
  5212. # Reset menu
  5213. self.ui.recent.clear()
  5214. self.recent = []
  5215. try:
  5216. f = open(self.data_path + '/recent.json', 'w')
  5217. except IOError:
  5218. App.log.error("Failed to open recent items file for writing.")
  5219. return
  5220. json.dump(self.recent, f)
  5221. # Reset menu
  5222. self.ui.recent.clear()
  5223. # Create menu items
  5224. for recent in self.recent:
  5225. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5226. try:
  5227. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5228. # Attach callback
  5229. o = make_callback(openers[recent["kind"]], recent['filename'])
  5230. action.triggered.connect(o)
  5231. self.ui.recent.addAction(action)
  5232. except KeyError:
  5233. App.log.error("Unsupported file type: %s" % recent["kind"])
  5234. # Last action in Recent Files menu is one that Clear the content
  5235. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5236. clear_action.triggered.connect(reset_recent)
  5237. self.ui.recent.addSeparator()
  5238. self.ui.recent.addAction(clear_action)
  5239. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5240. # self.ui.menufilerecent.set_submenu(recent_menu)
  5241. # recent_menu.show_all()
  5242. # self.ui.recent.show()
  5243. self.log.debug("Recent items list has been populated.")
  5244. def setup_component_editor(self):
  5245. # label = QtWidgets.QLabel("Choose an item from Project")
  5246. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5247. sel_title = QtWidgets.QTextEdit(
  5248. '<b>Shortcut Key List</b>')
  5249. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5250. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5251. # font = self.sel_title.font()
  5252. # font.setPointSize(12)
  5253. # self.sel_title.setFont(font)
  5254. selected_text = '''
  5255. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5256. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5257. The normal flow when working in FlatCAM is the following:</span></p>
  5258. <ol>
  5259. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5260. <br />
  5261. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5262. &nbsp;</li>
  5263. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5264. <br />
  5265. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5266. <br />
  5267. You can change the parameters in this screen and the flow direction is like this:<br />
  5268. <br />
  5269. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5270. </ol>
  5271. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5272. '''
  5273. sel_title.setText(selected_text)
  5274. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5275. self.ui.selected_scroll_area.setWidget(sel_title)
  5276. # tool_title = QtWidgets.QTextEdit(
  5277. # '<b>Shortcut Key List</b>')
  5278. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5279. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5280. # # font = self.sel_title.font()
  5281. # # font.setPointSize(12)
  5282. # # self.sel_title.setFont(font)
  5283. #
  5284. # tool_text = '''
  5285. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5286. #
  5287. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5288. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5289. #
  5290. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5291. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5292. #
  5293. # <ol>
  5294. # </ol>
  5295. #
  5296. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5297. #
  5298. # '''
  5299. #
  5300. # tool_title.setText(tool_text)
  5301. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5302. #
  5303. # self.ui.tool_scroll_area.setWidget(tool_title)
  5304. def setup_obj_classes(self):
  5305. """
  5306. Sets up application specifics on the FlatCAMObj class.
  5307. :return: None
  5308. """
  5309. FlatCAMObj.app = self
  5310. ObjectCollection.app = self
  5311. FCProcess.app = self
  5312. FCProcessContainer.app = self
  5313. def version_check(self):
  5314. """
  5315. Checks for the latest version of the program. Alerts the
  5316. user if theirs is outdated. This method is meant to be run
  5317. in a separate thread.
  5318. :return: None
  5319. """
  5320. self.log.debug("version_check()")
  5321. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5322. full_url = App.version_url + \
  5323. "?s=" + str(self.defaults['global_serial']) + \
  5324. "&v=" + str(self.version) + \
  5325. "&os=" + str(self.os) + \
  5326. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5327. else:
  5328. # no_stats dict; just so it won't break things on website
  5329. no_ststs_dict = {}
  5330. no_ststs_dict["global_ststs"] = {}
  5331. full_url = App.version_url + \
  5332. "?s=" + str(self.defaults['global_serial']) + \
  5333. "&v=" + str(self.version) + \
  5334. "&os=" + str(self.os) + \
  5335. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5336. App.log.debug("Checking for updates @ %s" % full_url)
  5337. ### Get the data
  5338. try:
  5339. f = urllib.request.urlopen(full_url)
  5340. except:
  5341. # App.log.warning("Failed checking for latest version. Could not connect.")
  5342. self.log.warning("Failed checking for latest version. Could not connect.")
  5343. self.inform.emit("[WARNING_NOTCL] Failed checking for latest version. Could not connect.")
  5344. return
  5345. try:
  5346. data = json.load(f)
  5347. except Exception as e:
  5348. App.log.error("Could not parse information about latest version.")
  5349. self.inform.emit("[ERROR_NOTCL] Could not parse information about latest version.")
  5350. App.log.debug("json.load(): %s" % str(e))
  5351. f.close()
  5352. return
  5353. f.close()
  5354. ### Latest version?
  5355. if self.version >= data["version"]:
  5356. App.log.debug("FlatCAM is up to date!")
  5357. self.inform.emit("[success] FlatCAM is up to date!")
  5358. return
  5359. App.log.debug("Newer version available.")
  5360. self.message.emit(
  5361. "Newer Version Available",
  5362. str("There is a newer version of FlatCAM " +
  5363. "available for download:<br><br>" +
  5364. "<B>" + data["name"] + "</b><br>" +
  5365. data["message"].replace("\n", "<br>")),
  5366. "info"
  5367. )
  5368. def on_zoom_fit(self, event):
  5369. """
  5370. Callback for zoom-out request. This can be either from the corresponding
  5371. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5372. with axes limits from the geometry bounds of all objects.
  5373. :param event: Ignored.
  5374. :return: None
  5375. """
  5376. self.plotcanvas.fit_view()
  5377. def disable_all_plots(self):
  5378. self.report_usage("disable_all_plots()")
  5379. self.disable_plots(self.collection.get_list())
  5380. self.inform.emit("[success]All plots disabled.")
  5381. def disable_other_plots(self):
  5382. self.report_usage("disable_other_plots()")
  5383. self.disable_plots(self.collection.get_non_selected())
  5384. self.inform.emit("[success]All non selected plots disabled.")
  5385. def enable_all_plots(self):
  5386. self.report_usage("enable_all_plots()")
  5387. self.enable_plots(self.collection.get_list())
  5388. self.inform.emit("[success]All plots enabled.")
  5389. # TODO: FIX THIS
  5390. '''
  5391. By default this is not threaded
  5392. If threaded the app give warnings like this:
  5393. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5394. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5395. '''
  5396. def enable_plots(self, objects, threaded=False):
  5397. if threaded is True:
  5398. def worker_task(app_obj):
  5399. percentage = 0.1
  5400. try:
  5401. delta = 0.9 / len(objects)
  5402. except ZeroDivisionError:
  5403. self.progress.emit(0)
  5404. return
  5405. for obj in objects:
  5406. obj.options['plot'] = True
  5407. percentage += delta
  5408. self.progress.emit(int(percentage*100))
  5409. self.progress.emit(0)
  5410. self.plots_updated.emit()
  5411. self.collection.update_view()
  5412. # Send to worker
  5413. # self.worker.add_task(worker_task, [self])
  5414. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5415. else:
  5416. for obj in objects:
  5417. obj.options['plot'] = True
  5418. self.progress.emit(0)
  5419. self.plots_updated.emit()
  5420. self.collection.update_view()
  5421. # TODO: FIX THIS
  5422. '''
  5423. By default this is not threaded
  5424. If threaded the app give warnings like this:
  5425. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5426. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5427. '''
  5428. def disable_plots(self, objects, threaded=False):
  5429. # TODO: This method is very similar to replot_all. Try to merge.
  5430. """
  5431. Disables plots
  5432. :param objects: list
  5433. Objects to be disabled
  5434. :return:
  5435. """
  5436. if threaded is True:
  5437. self.progress.emit(10)
  5438. def worker_task(app_obj):
  5439. percentage = 0.1
  5440. try:
  5441. delta = 0.9 / len(objects)
  5442. except ZeroDivisionError:
  5443. self.progress.emit(0)
  5444. return
  5445. for obj in objects:
  5446. obj.options['plot'] = False
  5447. percentage += delta
  5448. self.progress.emit(int(percentage*100))
  5449. self.progress.emit(0)
  5450. self.plots_updated.emit()
  5451. self.collection.update_view()
  5452. # Send to worker
  5453. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5454. else:
  5455. for obj in objects:
  5456. obj.options['plot'] = False
  5457. self.plots_updated.emit()
  5458. self.collection.update_view()
  5459. def clear_plots(self):
  5460. objects = self.collection.get_list()
  5461. for obj in objects:
  5462. obj.clear(obj == objects[-1])
  5463. # Clear pool to free memory
  5464. self.clear_pool()
  5465. def generate_cnc_job(self, objects):
  5466. self.report_usage("generate_cnc_job()")
  5467. # for obj in objects:
  5468. # obj.generatecncjob()
  5469. for obj in objects:
  5470. obj.on_generatecnc_button_click()
  5471. def save_project(self, filename):
  5472. """
  5473. Saves the current project to the specified file.
  5474. :param filename: Name of the file in which to save.
  5475. :type filename: str
  5476. :return: None
  5477. """
  5478. self.log.debug("save_project()")
  5479. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5480. ## Capture the latest changes
  5481. # Current object
  5482. try:
  5483. self.collection.get_active().read_form()
  5484. except:
  5485. self.log.debug("[WARNING] There was no active object")
  5486. pass
  5487. # Project options
  5488. self.options_read_form()
  5489. # Serialize the whole project
  5490. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5491. "options": self.options,
  5492. "version": self.version}
  5493. # Open file
  5494. try:
  5495. f = open(filename, 'w')
  5496. except IOError:
  5497. App.log.error("[ERROR] Failed to open file for saving: %s", filename)
  5498. return
  5499. # Write
  5500. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5501. f.close()
  5502. # verification of the saved project
  5503. # Open and parse
  5504. try:
  5505. saved_f = open(filename, 'r')
  5506. except IOError:
  5507. self.inform.emit("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it." % filename)
  5508. return
  5509. try:
  5510. saved_d = json.load(saved_f, object_hook=dict2obj)
  5511. except:
  5512. self.inform.emit("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it." % filename)
  5513. f.close()
  5514. return
  5515. saved_f.close()
  5516. if 'version' in saved_d:
  5517. self.inform.emit("[success] Project saved to: %s" % filename)
  5518. else:
  5519. self.inform.emit("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it." % filename)
  5520. def on_options_app2project(self):
  5521. """
  5522. Callback for Options->Transfer Options->App=>Project. Copies options
  5523. from application defaults to project defaults.
  5524. :return: None
  5525. """
  5526. self.report_usage("on_options_app2project")
  5527. self.defaults_read_form()
  5528. self.options.update(self.defaults)
  5529. self.options_write_form()
  5530. def on_options_project2app(self):
  5531. """
  5532. Callback for Options->Transfer Options->Project=>App. Copies options
  5533. from project defaults to application defaults.
  5534. :return: None
  5535. """
  5536. self.report_usage("on_options_project2app")
  5537. self.options_read_form()
  5538. self.defaults.update(self.options)
  5539. self.defaults_write_form()
  5540. def on_options_project2object(self):
  5541. """
  5542. Callback for Options->Transfer Options->Project=>Object. Copies options
  5543. from project defaults to the currently selected object.
  5544. :return: None
  5545. """
  5546. self.report_usage("on_options_project2object")
  5547. self.options_read_form()
  5548. obj = self.collection.get_active()
  5549. if obj is None:
  5550. self.inform.emit("WARNING: No object selected.")
  5551. return
  5552. for option in self.options:
  5553. if option.find(obj.kind + "_") == 0:
  5554. oname = option[len(obj.kind) + 1:]
  5555. obj.options[oname] = self.options[option]
  5556. obj.to_form() # Update UI
  5557. def on_options_object2project(self):
  5558. """
  5559. Callback for Options->Transfer Options->Object=>Project. Copies options
  5560. from the currently selected object to project defaults.
  5561. :return: None
  5562. """
  5563. self.report_usage("on_options_object2project")
  5564. obj = self.collection.get_active()
  5565. if obj is None:
  5566. self.inform.emit("WARNING: No object selected.")
  5567. return
  5568. obj.read_form()
  5569. for option in obj.options:
  5570. if option in ['name']: # TODO: Handle this better...
  5571. continue
  5572. self.options[obj.kind + "_" + option] = obj.options[option]
  5573. self.options_write_form()
  5574. def on_options_object2app(self):
  5575. """
  5576. Callback for Options->Transfer Options->Object=>App. Copies options
  5577. from the currently selected object to application defaults.
  5578. :return: None
  5579. """
  5580. self.report_usage("on_options_object2app")
  5581. obj = self.collection.get_active()
  5582. if obj is None:
  5583. self.inform.emit("WARNING: No object selected.")
  5584. return
  5585. obj.read_form()
  5586. for option in obj.options:
  5587. if option in ['name']: # TODO: Handle this better...
  5588. continue
  5589. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5590. self.defaults_write_form()
  5591. def on_options_app2object(self):
  5592. """
  5593. Callback for Options->Transfer Options->App=>Object. Copies options
  5594. from application defaults to the currently selected object.
  5595. :return: None
  5596. """
  5597. self.report_usage("on_options_app2object")
  5598. self.defaults_read_form()
  5599. obj = self.collection.get_active()
  5600. if obj is None:
  5601. self.inform.emit("WARNING: No object selected.")
  5602. return
  5603. for option in self.defaults:
  5604. if option.find(obj.kind + "_") == 0:
  5605. oname = option[len(obj.kind) + 1:]
  5606. obj.options[oname] = self.defaults[option]
  5607. obj.to_form() # Update UI
  5608. # end of file